org.jooq.ResultQuery Java Examples

The following examples show how to use org.jooq.ResultQuery. 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: RelationIncluder.java    From java-crud-api with MIT License 6 votes vote down vote up
private HabtmValues getHabtmEmptyValues(ReflectedTable t1, ReflectedTable t2, ReflectedTable t3, DSLContext dsl,
		ArrayList<Record> records) {
	HashMap<Object, ArrayList<Object>> pkValues = getPkEmptyValues(t1, records);
	HashMap<Object, Object> fkValues = new HashMap<>();

	Field<Object> fk1 = t3.getFksTo(t1.getName()).get(0);
	Field<Object> fk2 = t3.getFksTo(t2.getName()).get(0);
	List<Field<?>> fields = Arrays.asList(fk1, fk2);
	Condition condition = fk1.in(pkValues.keySet());
	ResultQuery<org.jooq.Record> query = dsl.select(fields).from(t3).where(condition);
	for (org.jooq.Record record : query.fetch()) {
		Object val1 = record.get(fk1);
		Object val2 = record.get(fk2);
		pkValues.get(val1).add(val2);
		fkValues.put(val2, null);
	}

	return new HabtmValues(pkValues, fkValues);
}
 
Example #2
Source File: PostgresPersistenceManager.java    From FROST-Server with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Gets the requested entity and locks the row for update. End the
 * transaction quickly to release the lock.
 *
 * @param entityType The type of entity to fetch.
 * @param id The ID of the entity to fetch.
 * @param forUpdate if true, lock the entities row for update.
 * @return the requested entity.
 */
private Entity get(EntityType entityType, Id id, boolean forUpdate, Query query) {
    QueryBuilder<J> psb = new QueryBuilder<>(this, settings, getPropertyResolver());
    ResultQuery sqlQuery = psb.forTypeAndId(entityType, id)
            .usingQuery(query)
            .forUpdate(forUpdate)
            .buildSelect();

    Record record = sqlQuery.fetchAny();
    if (record == null) {
        return null;
    }

    EntityFactory<? extends Entity, J> factory;
    factory = getEntityFactories().getFactoryFor(entityType);
    return factory.create(record, null, new DataSize());
}
 
Example #3
Source File: ResultBuilder.java    From FROST-Server with GNU Lesser General Public License v3.0 6 votes vote down vote up
private <R extends Record> Cursor<R> timeQuery(ResultQuery<R> query) {
    if (persistenceSettings.isTimeoutQueries()) {
        query.queryTimeout(persistenceSettings.getQueryTimeout());
    }
    if (!persistenceSettings.isLogSlowQueries()) {
        return query.fetchLazy();
    }
    long start = System.currentTimeMillis();
    Cursor<R> result;
    try {
        result = query.fetchLazy();
    } catch (DataAccessException exc) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.info("Failed to run query:\n{}", query.getSQL(ParamType.INLINED));
        }
        throw new IllegalStateException("Failed to run query: " + exc.getMessage());
    }
    long end = System.currentTimeMillis();
    long duration = end - start;
    if (LOGGER.isInfoEnabled() && duration > persistenceSettings.getSlowQueryThreshold()) {
        LOGGER.info("Slow Query executed in {} ms:\n{}", duration, query.getSQL(ParamType.INLINED));
    }
    return result;
}
 
Example #4
Source File: QueryBuilder.java    From FROST-Server with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Build a count query.
 *
 * @return the count query.
 */
public ResultQuery<Record1<Integer>> buildCount() {
    gatherData();

    DSLContext dslContext = pm.getDslContext();
    AggregateFunction<Integer> count;
    if (queryState.isDistinctRequired()) {
        count = DSL.countDistinct(queryState.getSqlMainIdField());
    } else {
        count = DSL.count(queryState.getSqlMainIdField());
    }
    SelectConditionStep<Record1<Integer>> query = dslContext.select(count)
            .from(queryState.getSqlFrom())
            .where(queryState.getSqlWhere());

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(GENERATED_SQL, query.getSQL(ParamType.INDEXED));
    }
    return query;
}
 
Example #5
Source File: SelectQueryMapper.java    From SimpleFlatMapper with MIT License 6 votes vote down vote up
private <SET extends TableLike & ResultQuery> SetRowMapper<ResultSet, ResultSet, T, SQLException> getMapper(SET source) {
    try {
        Field[] fields = getFields(source);

        JooqFieldKey[] keys = new JooqFieldKey[fields.length];
        for (int i = 0; i < fields.length; i++) {
            keys[i] = new JooqFieldKey(fields[i], i);
        }

        MapperKey<JooqFieldKey> mapperKey = new MapperKey<JooqFieldKey>(keys);

        SetRowMapper<ResultSet, ResultSet, T, SQLException> mapper = mapperCache.get(mapperKey);

        if (mapper == null) {
            mapper = buildMapper(fields);
            mapperCache.add(mapperKey, mapper);
        }

        return mapper;
    } catch (Exception e) {
        throw new org.jooq.exception.MappingException(e.getMessage(), e);
    }
}
 
Example #6
Source File: RelationIncluder.java    From java-crud-api with MIT License 5 votes vote down vote up
private void addPkRecords(ReflectedTable t1, ReflectedTable t2, HashMap<Object, ArrayList<Object>> pkValues,
		Params params, DSLContext dsl, ArrayList<Record> records) {
	List<Field<Object>> fks = t2.getFksTo(t1.getName());
	ArrayList<Field<?>> fields = columns.getNames(t2, false, params);
	Condition condition = DSL.falseCondition();
	for (Field<Object> fk : fks) {
		condition = condition.or(fk.in(pkValues.keySet()));
	}
	ResultQuery<org.jooq.Record> query = dsl.select(fields).from(t2).where(condition);
	for (org.jooq.Record record : query.fetch()) {
		records.add(Record.valueOf(record.intoMap()));
	}
}
 
Example #7
Source File: PostgresPersistenceManager.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public boolean validatePath(ResourcePath path) {
    PathElement element = path.getIdentifiedElement();
    if (element == null) {
        return true;
    }
    ResourcePath tempPath = new ResourcePath();
    int idCount = 0;
    while (element != null) {
        if (element instanceof PathElementEntity) {
            PathElementEntity entityPathElement = (PathElementEntity) element;
            Id id = entityPathElement.getId();
            if (id != null) {
                idCount++;
                if (!getEntityFactories().entityExists(this, entityPathElement.getEntityType(), id)) {
                    return false;
                }
            }
        }
        tempPath.addPathElement(0, element);
        element = element.getParent();
    }
    if (idCount < 2) {
        return true;
    }
    QueryBuilder<J> psb = new QueryBuilder<>(this, settings, getPropertyResolver());
    ResultQuery<Record1<Integer>> query = psb
            .forPath(tempPath)
            .buildCount();
    Integer count = query.fetchOne().component1();
    return count == 1;
}
 
Example #8
Source File: ResultBuilder.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void fetchAndAddCount(EntitySet<? extends Entity> entitySet) {
    if (staQuery.isCountOrDefault()) {
        ResultQuery<Record1<Integer>> countQuery = sqlQueryBuilder.buildCount();
        try (Cursor<Record1<Integer>> countCursor = timeQuery(countQuery)) {
            Integer count = countCursor
                    .fetchNext()
                    .component1();
            entitySet.setCount(count);
        }
    }
}
 
Example #9
Source File: RelationIncluder.java    From java-crud-api with MIT License 5 votes vote down vote up
private void addFkRecords(ReflectedTable t2, HashMap<Object, Object> fkValues, Params params, DSLContext dsl,
		ArrayList<Record> records) {
	Field<Object> pk = t2.getPk();
	ArrayList<Field<?>> fields = columns.getNames(t2, false, params);
	ResultQuery<org.jooq.Record> query = dsl.select(fields).from(t2).where(pk.in(fkValues.keySet()));
	for (org.jooq.Record record : query.fetch()) {
		records.add(Record.valueOf(record.intoMap()));
	}
}
 
Example #10
Source File: SelectQueryMapper.java    From SimpleFlatMapper with MIT License 5 votes vote down vote up
private <SET extends TableLike & ResultQuery> Field[] getFields(SET source) {
    if (source instanceof Select) {
        List<Field<?>> select = ((Select<?>) source).getSelect();
        return select.toArray(new Field[0]);
    }
    return source.fields();
}
 
Example #11
Source File: SelectQueryMapper.java    From SimpleFlatMapper with MIT License 5 votes vote down vote up
public <SET extends TableLike & ResultQuery> AutoCloseableEnumerable<T> enumerate(SET source)
        throws MappingException {
    SetRowMapper<ResultSet, ResultSet, T, SQLException> mapper = getMapper(source);
    try {
        final ResultSet rs = source.fetchResultSet();
        final Enumerable<T> enumerable = new ExceptionTranslatorEnumerable<T>(mapper.enumerate(rs));
        return new AutoCloseableEnumerable<T>(enumerable, closer(rs));
    } catch (SQLException e) {
        throw new DataAccessException(e.getMessage(), e);
    }
}
 
Example #12
Source File: QueryBuilder.java    From FROST-Server with GNU Lesser General Public License v3.0 4 votes vote down vote up
public ResultQuery<Record> buildSelect() {
    gatherData();

    if (queryState.getSqlSelectFields() == null) {
        queryState.setSqlSelectFields(Collections.emptySet());
    }

    DSLContext dslContext = pm.getDslContext();
    SelectSelectStep<Record> selectStep;
    if (queryState.isDistinctRequired()) {
        addOrderPropertiesToSelected();
        selectStep = dslContext.selectDistinct(queryState.getSqlSelectFields());
    } else {
        selectStep = dslContext.select(queryState.getSqlSelectFields());
    }
    SelectConditionStep<Record> whereStep = selectStep.from(queryState.getSqlFrom())
            .where(queryState.getSqlWhere());

    final List<OrderField> sortFields = queryState.getSqlSortFields().getSqlSortFields();
    SelectSeekStepN<Record> orderByStep = whereStep.orderBy(sortFields.toArray(new OrderField[sortFields.size()]));

    int skip = 0;
    int count;
    if (single) {
        count = 2;
    } else if (staQuery != null) {
        count = staQuery.getTopOrDefault() + 1;
        skip = staQuery.getSkip(0);
    } else {
        count = 1;
    }
    SelectWithTiesAfterOffsetStep<Record> limit = orderByStep.limit(skip, count);

    if (forUpdate) {
        return limit.forUpdate();
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(GENERATED_SQL, limit.getSQL(ParamType.INDEXED));
    }
    return limit;
}
 
Example #13
Source File: JooqJpaRepository.java    From blog-examples with Apache License 2.0 4 votes vote down vote up
@Override
public T findOne(ResultQuery q) {
	Class<T> type = entityInformation.getJavaType();
	return q.fetchOne().into(type);
}
 
Example #14
Source File: UnifiedQueryExecutor.java    From vertx-jooq with MIT License 2 votes vote down vote up
/**
 * @param queryFunction a function to run a arbitrary {@code ResultQuery} on a {@code DSLContext} provided by this {@code QueryExecutor}.
 * @param <R> the record type
 * @return the result type returned for this query. This varies on the VertxDAO-subtypes, e.g. {@code Future<QueryResult>}.
 * @see QueryResult
 */
public <R extends Record> QUERY query(Function<DSLContext, ? extends ResultQuery<R>> queryFunction);
 
Example #15
Source File: AsyncQueryExecutor.java    From vertx-jooq with MIT License 2 votes vote down vote up
/**
 * Executes the given query and returns at most one result as a JsonObject asynchronously. If more than
 * one item is returned by the underlying client, the returned result will be in a failure-state.
 * @param <Q> the Record-type
 * @param queryFunction the query
 * @return the result or <code>null</code>.
 */
public <Q extends Record> FIND_ONE_JSON findOneJson(Function<DSLContext, ? extends ResultQuery<Q>> queryFunction);
 
Example #16
Source File: AsyncQueryExecutor.java    From vertx-jooq with MIT License 2 votes vote down vote up
/**
 * Executes the given query and returns the results as a List of JsonObjects asynchronously.
 * @param <Q> the Record-type
 * @param queryFunction the query
 * @return the results, never <code>null</code>.
 */
public <Q extends Record> FIND_MANY_JSON findManyJson(Function<DSLContext, ? extends ResultQuery<Q>> queryFunction);
 
Example #17
Source File: ReactiveQueryExecutor.java    From vertx-jooq with MIT License 2 votes vote down vote up
/**
 * Executes the given query and returns at most one result as a {@code Row} asynchronously. If more than
 * one item is returned by the underlying client, the returned result will be in a failure-state.
 * @param <Q> the Record-type
 * @param queryFunction the query
 * @return the result or <code>null</code>.
 */
public <Q extends Record> FIND_ONE_ROW findOneRow(Function<DSLContext, ? extends ResultQuery<Q>> queryFunction);
 
Example #18
Source File: ReactiveQueryExecutor.java    From vertx-jooq with MIT License 2 votes vote down vote up
/**
 * Executes the given query and returns the results as a List of {@code Row}s asynchronously.
 * @param <Q> the Record-type
 * @param queryFunction the query
 * @return the results, never <code>null</code>.
 */
public <Q extends Record> FIND_MANY_ROW findManyRow(Function<DSLContext, ? extends ResultQuery<Q>> queryFunction);
 
Example #19
Source File: JooqQueryExecutor.java    From blog-examples with Apache License 2.0 votes vote down vote up
T findOne(ResultQuery q);