@NotNull @Override public Condition buildCondition(final List<Object> values) { if (isConditionSupplier()) throw new IllegalStateException("Condition supplier is not null"); // TODO No checking on list size as API should be safe on that but if buildCondition in FilteringJooq is overridden then cannot make sure value count is correct if (conditionCreator2 != null) { return throwIfConditionIsNull(conditionCreator2.apply(values.get(0), values.get(1)), "Condition cannot be null"); } // TODO could eventually allow Value1 but would require to try a casting to it of the function, if exception then we apply the value without casting otherwise we create the value // No checking as API does not allow to specify for one value to use Value1<T1> if (values.size() == 1) { return throwIfConditionIsNull(conditionCreator.apply(values.get(0)), "Condition cannot be null"); } // More than 2 values will send back a Value object final Value value = new ValueImpl(values); return throwIfConditionIsNull(conditionCreator.apply(value), "Condition cannot be null"); }
public StorageResult<E> update(E entity, QueryParams queryParams, Map<String, Object> queryMap) { logger.info("Update table {} entry by {}", getProviderTable(), entity); try { int affectedRows = -1; Condition c = null; if (queryParams != null) { c = addCondition(queryParams, queryMap); } else { c = DSL.field("id").eq(entity.getId()); // ����Id���� } affectedRows = this.updateRecord(entity, c); if (affectedRows == -1) { return new StorageResult<E>(StatusCodes.COMMAND_FAILED, false); } StorageResult<E> updRes = new StorageResult<E>(StatusCodes.NO_CONTENT, true); // updRes.setCount((long) affectedRows); return updRes; } catch (Exception e) { logger.error("PUT {} ERROR { }", entity, e); } return new StorageResult<E>(StatusCodes.INTERNAL_SERVER_ERROR, false); }
public StorageResult<E> delete(Object... ids) { logger.info("Delete table {} entry by {}", getProviderTable(), ids); try { if (ids == null) { new StorageResult<E>(StatusCodes.NO_CONTENT, true); } Condition c = DSL.field("id").in(ids); int affectedRows = -1; affectedRows = this.deleteRecord(c); if (affectedRows == -1) { return new StorageResult<E>(StatusCodes.COMMAND_FAILED, false); } StorageResult<E> updRes = new StorageResult<E>(StatusCodes.NO_CONTENT, true); return updRes; } catch (Exception e) { logger.error("Delte {} ERROR { }", ids, e); } return new StorageResult<E>(StatusCodes.INTERNAL_SERVER_ERROR, false); }
@Override public <T> ConditionProvider<T> getConditionProvider(final Field<T> field) { return new MultiParamConditionProvider<T>(field) { @SuppressWarnings("unchecked") @Override public Condition getCondition(Collection<T> values) { List<Number> valueList = new ArrayList<Number>((Collection<? extends Number>) values); Preconditions.checkArgument(valueList.size() == 2, "Range filters require exactly 2 parameters"); Collections.sort(valueList, NUMBER_COMPARATOR); return field.between((T) valueList.get(0), (T) valueList.get(1)); } }; }
@Override public <T> ConditionProvider<T> getConditionProvider(final Field<T> field) { return new MultiParamConditionProvider<T>(field) { @Override public Condition getCondition(Collection<T> values) { Iterator<T> iter = values.iterator(); Condition notLikeCondition = field.notLike((String) iter.next(), '!'); while (iter.hasNext()) { notLikeCondition = notLikeCondition.and(field.notLike((String) iter.next(), '!')); } return notLikeCondition; } }; }
@Override public Condition translate(PredicatesHolder predicatesHolder) { Set<Condition> predicateFilters = predicatesHolder.getPredicates().stream() .map(this::extractCondition).collect(Collectors.toSet()); Set<Condition> childFilters = predicatesHolder.getChildren().stream() .map(this::translate).collect(Collectors.toSet()); predicateFilters.addAll(childFilters); if (predicateFilters.size() == 0) return DSL.trueCondition(); if (predicateFilters.size() == 1) return predicateFilters.iterator().next(); if (predicatesHolder.getClause().equals(PredicatesHolder.Clause.And)) { return predicateFilters.stream().reduce(Condition::and).get(); } else if (predicatesHolder.getClause().equals(PredicatesHolder.Clause.Or)) { return predicateFilters.stream().reduce(Condition::or).get(); } else throw new IllegalArgumentException("Unexpected clause in predicatesHolder: " + predicatesHolder); }
private Condition handleConnectiveP(String key, ConnectiveP predicate) { List<P> predicates = predicate.getPredicates(); List<Condition> queries = predicates.stream().map(p -> { if (p instanceof ConnectiveP) return handleConnectiveP(key, (ConnectiveP) p); Object pValue = p.getValue(); BiPredicate pBiPredicate = p.getBiPredicate(); return predicateToQuery(key, pValue, pBiPredicate); }).collect(Collectors.toList()); Condition condition = queries.get(0); if (predicate instanceof AndP){ for (int i = 1; i < queries.size(); i++) { condition = condition.and(queries.get(i)); } } else if (predicate instanceof OrP){ for (int i = 1; i < queries.size(); i++) { condition = condition.or(queries.get(i)); } } else throw new IllegalArgumentException("Connective predicate not supported by unipop"); return condition; }
private Condition predicateToQuery(String field, Object value, BiPredicate<?, ?> biPredicate) { if (biPredicate instanceof Compare) { return getCompareCondition(value, biPredicate, field(field)); } else if (biPredicate instanceof Contains) { Condition x = getContainsCondition(value, biPredicate, field(field)); if (x != null) return x; } else if (biPredicate instanceof Text.TextPredicate) { return getTextCondition(value, biPredicate, field(field)); } else if (biPredicate instanceof Date.DatePredicate) { try { return getDateCondition(value, biPredicate, field(field)); } catch (ParseException e) { throw new IllegalArgumentException("cant convert to date"); } } throw new IllegalArgumentException("can't create condition"); }
private Condition getCompareCondition(Object value, BiPredicate<?, ?> biPredicate, Field<Object> field) { String predicateString = biPredicate.toString(); switch (predicateString) { case ("eq"): return field.eq(value); case ("neq"): return field.notEqual(value); case ("gt"): return field.greaterThan(value); case ("gte"): return field.greaterOrEqual(value); case ("lt"): return field.lessThan(value); case ("lte"): return field.lessOrEqual(value); case ("inside"): List items = (List) value; Object firstItem = items.get(0); Object secondItem = items.get(1); return field.between(firstItem, secondItem); default: throw new IllegalArgumentException("predicate not supported in has step: " + biPredicate.toString()); } }
private Condition getContainsCondition(Object value, BiPredicate<?, ?> biPredicate, Field<Object> field) { if (biPredicate == Contains.without) { if (value == null) { return field.isNull(); } else { return field.notIn(value); } } else if (biPredicate == Contains.within) { if (value == null) { return field.isNotNull(); } else { return field.in(((Collection) value).toArray()); } } return null; }
private Condition getTextCondition(Object value, BiPredicate<?, ?> biPredicate, Field<Object> field) { String predicateString = biPredicate.toString(); switch (predicateString) { case ("LIKE"): return field.like(value.toString().replace("*", "%")); case ("UNLIKE"): return field.notLike(value.toString().replace("*", "%")); case ("REGEXP"): return field.likeRegex(value.toString()); case ("UNREGEXP"): return field.notLikeRegex(value.toString()); case ("PREFIX"): return field.like(value.toString() + "%"); case ("UNPREFIX"): return field.notLike(value.toString() + "%"); default: throw new IllegalArgumentException("predicate not supported in has step: " + biPredicate.toString()); } }
private void addOnlyLastFilter() { if (filter.isOnlyLastByStatus() || filter.isOnlyLastByProblem() || filter.isOnlyLastByTeam()) { final Submissions s2 = SUBMISSIONS.as("s2"); Condition condition = SUBMISSIONS.SUBMISSION_ID.lessThan(s2.SUBMISSION_ID); if (filter.isOnlyLastByTeam()) { condition = condition.and(s2.TEAM_ID.eq(SUBMISSIONS.TEAM_ID)); } if (filter.isOnlyLastByProblem()) { condition = condition.and(s2.TASK_ID.eq(SUBMISSIONS.TASK_ID)); } if (filter.isOnlyLastByStatus()) { condition = condition.and(s2.RESULT.eq(SUBMISSIONS.RESULT)); } step.leftOuterJoin(s2).on(condition); step.where(s2.SUBMISSION_ID.isNull()); } }
@Override public SubmissionListView getSubmissions(final SubmissionListFilter filter, final Integer page, final boolean isAdmin) { int itemsPerPage = SecurityUtils.getItemsPerPage(); final SelectJoinStep<Record> submissionSelect = getSubmissionSelect(); SubmissionFilterAppender.appendOn(filter, submissionSelect); if (!isAdmin) { final Condition isNotAdmin = USERS.ROLE.ne(Constants.ADMIN_ROLE_VALUE); submissionSelect.where(isNotAdmin); if (filter.hasStatusFilter()) { submissionSelect.where(isFrozenField.isFalse()); } } final List<SubmissionDetailView> submissions = submissionSelect.orderBy(SUBMISSIONS.CREATED.desc()) .limit(itemsPerPage) .offset(page * itemsPerPage) .fetch(submissionDetailRecordMapper); return new SubmissionListView(submissions); }
@Override public List<? extends ProjectMember> getProjectMembersByIdentity(long projectId, Set<Identity> identities) { Condition allMembers = DSL.falseCondition(); for (Identity identity : identities) { allMembers = allMembers.or(PROJECT_MEMBER.EXTERNAL_ID.eq(identity.getExternalId()) .and(PROJECT_MEMBER.EXTERNAL_ID_TYPE.eq(identity.getExternalIdType())) .and(PROJECT_MEMBER.REMOVED.isNull()) .and(PROJECT_MEMBER.STATE.eq(CommonStatesConstants.ACTIVE)) .and(PROJECT_MEMBER.PROJECT_ID.eq(projectId))); } SelectQuery<Record> query = create().selectQuery(); query.addFrom(PROJECT_MEMBER); query.addConditions(allMembers); query.setDistinct(true); return query.fetchInto(PROJECT_MEMBER); }
@Override public boolean isProjectOwner(long projectId, Long usingAccount, boolean isAdmin, Set<Identity> identities) { if (identities == null) { return false; } if (isAdmin) { return true; } if (usingAccount != null && usingAccount.equals(projectId)) { return false; } Set<ProjectMemberRecord> projectMembers = new HashSet<>(); Condition allMembers = DSL.falseCondition(); for (Identity id : identities) { allMembers = allMembers.or(PROJECT_MEMBER.EXTERNAL_ID.eq(id.getExternalId()) .and(PROJECT_MEMBER.EXTERNAL_ID_TYPE.eq(id.getExternalIdType())) .and(PROJECT_MEMBER.ROLE.eq(ProjectConstants.OWNER)) .and(PROJECT_MEMBER.PROJECT_ID.eq(projectId)) .and(PROJECT_MEMBER.STATE.eq(CommonStatesConstants.ACTIVE)) .and(PROJECT_MEMBER.REMOVED.isNull())); } projectMembers.addAll(create().selectFrom(PROJECT_MEMBER).where(allMembers).fetch()); return !projectMembers.isEmpty(); }
@Override public boolean isProjectMember(long projectId, Long usingAccount, boolean isAdmin, Set<Identity> identities) { if (identities == null) { return false; } if ((usingAccount != null && usingAccount.equals(projectId)) || isAdmin) { return true; } Set<ProjectMemberRecord> projectMembers = new HashSet<>(); Condition allMembers = DSL.falseCondition(); for (Identity id : identities) { allMembers = allMembers.or(PROJECT_MEMBER.EXTERNAL_ID.eq(id.getExternalId()) .and(PROJECT_MEMBER.EXTERNAL_ID_TYPE.eq(id.getExternalIdType())) .and(PROJECT_MEMBER.PROJECT_ID.eq(projectId)) .and(PROJECT_MEMBER.STATE.eq(CommonStatesConstants.ACTIVE)) .and(PROJECT_MEMBER.REMOVED.isNull())); } projectMembers.addAll(create().selectFrom(PROJECT_MEMBER).where(allMembers).fetch()); return !projectMembers.isEmpty(); }
@Override public Long getNextCreate(Long serviceId) { return transaction.doInTransactionResult(() -> { Long next = null; if (serviceId != null) { Long index = create().select(SERVICE.CREATE_INDEX) .from(SERVICE) .where(SERVICE.ID.eq(serviceId)) .forUpdate() .fetchAny().value1(); Condition cond = index == null ? SERVICE.CREATE_INDEX.isNull() : SERVICE.CREATE_INDEX.eq(index); next = index == null ? 1L : index+1; create().update(SERVICE) .set(SERVICE.CREATE_INDEX, next) .where(SERVICE.ID.eq(serviceId) .and(cond)) .execute(); } return next; }); }
@Override public List<? extends Credential> getApiKeys(Account account, String kind, boolean active) { if (kind == null) { kind = CredentialConstants.KIND_API_KEY; } Condition stateCondition = DSL.trueCondition(); if ( active ) { stateCondition = CREDENTIAL.STATE.eq(CommonStatesConstants.ACTIVE); } return create().selectFrom(CREDENTIAL) .where(CREDENTIAL.ACCOUNT_ID.eq(account.getId()) .and(CREDENTIAL.REMOVED.isNull()) .and(stateCondition) .and(CREDENTIAL.KIND.eq(kind))) .fetch(); }
protected Condition groupCondition() { if ( groupManager.shouldHandleWildcard() ) { return DSL.trueCondition(); } Condition condition = DSL.falseCondition(); Set<Long> supported = groupManager.supportedGroups(); if ( supported.size() > 0 ) { condition = AGENT.AGENT_GROUP_ID.in(supported); } if ( groupManager.shouldHandleUnassigned() ) { condition = condition.or(AGENT.AGENT_GROUP_ID.isNull()); } return condition; }
protected Condition getQueryOptionCondition(QueryOptions options) { Condition condition = null; if ( options.getHosts().size() > 0 ) { condition = append(condition, HOST.ID.in(options.getHosts())); } if ( options.getCompute() != null ) { condition = append(condition, HOST.COMPUTE_FREE.ge(options.getCompute())); } if ( options.getKind() != null ) { condition = append(condition, HOST.KIND.eq(options.getKind()).and(STORAGE_POOL.KIND.eq(options.getKind()))); } return condition == null ? DSL.trueCondition() : condition; }
protected void addMappingJoins(SelectQuery<?> query, Table<?> toTable, SchemaFactory schemaFactory, String fromType, Table<?> from, String asName, MapRelationship rel) { Table<?> mappingTable = JooqUtils.getTableFromRecordClass(rel.getMappingType()); /* We don't required the mapping type to be visible external, that's why we use the schemaFactory * from the objectManager, because it is the superset schemaFactory. */ String mappingType = getObjectManager().getSchemaFactory().getSchemaName(rel.getMappingType()); TableField<?, Object> fieldFrom = JooqUtils.getTableField(getMetaDataManager(), fromType, ObjectMetaDataManager.ID_FIELD); TableField<?, Object> fieldTo = JooqUtils.getTableField(getMetaDataManager(), mappingType, rel.getPropertyName()); TableField<?, Object> fieldRemoved = JooqUtils.getTableField(getMetaDataManager(), mappingType, ObjectMetaDataManager.REMOVED_FIELD); org.jooq.Condition cond = fieldFrom.eq(fieldTo.getTable().field(fieldTo.getName())).and(fieldRemoved == null ? DSL.trueCondition() : fieldRemoved.isNull()); query.addJoin(mappingTable, JoinType.LEFT_OUTER_JOIN, cond); fieldFrom = JooqUtils.getTableField(getMetaDataManager(), mappingType, rel.getOtherRelationship().getPropertyName()); fieldTo = JooqUtils.getTableField(getMetaDataManager(), schemaFactory.getSchemaName(rel.getObjectType()), ObjectMetaDataManager.ID_FIELD); cond = fieldFrom.eq(fieldTo.getTable().asTable(asName).field(fieldTo.getName())); query.addJoin(toTable, JoinType.LEFT_OUTER_JOIN, cond); }
protected org.jooq.Condition getJoinCondition(SchemaFactory schemaFactory, String fromType, Table<?> from, String asName, Relationship rel) { TableField<?, Object> fieldFrom = null; TableField<?, Object> fieldTo = null; switch(rel.getRelationshipType()) { case REFERENCE: fieldFrom = JooqUtils.getTableField(getMetaDataManager(), fromType, rel.getPropertyName()); fieldTo = JooqUtils.getTableField(getMetaDataManager(), schemaFactory.getSchemaName(rel.getObjectType()), ObjectMetaDataManager.ID_FIELD); break; case CHILD: fieldFrom = JooqUtils.getTableField(getMetaDataManager(), fromType, ObjectMetaDataManager.ID_FIELD); fieldTo = JooqUtils.getTableField(getMetaDataManager(), schemaFactory.getSchemaName(rel.getObjectType()), rel.getPropertyName()); break; default: throw new IllegalArgumentException("Illegal Relationship type [" + rel.getRelationshipType() + "]"); } if ( fieldFrom == null || fieldTo == null ) { throw new IllegalStateException("Failed to construction join query for [" + fromType + "] [" + from + "] [" + rel + "]"); } return fieldFrom.eq(fieldTo.getTable().as(asName).field(fieldTo.getName())); }
@Override protected void addAccountAuthorization(String type, Map<Object, Object> criteria, Policy policy) { super.addAccountAuthorization(type, criteria, policy); if ( ! policy.isOption(Policy.AUTHORIZED_FOR_ALL_ACCOUNTS) ) { TableField<?, Object> accountField = JooqUtils.getTableField(getMetaDataManager(), type, ObjectMetaDataManager.ACCOUNT_FIELD); TableField<?, Object> publicField = JooqUtils.getTableField(getMetaDataManager(), type, ObjectMetaDataManager.PUBLIC_FIELD); Object accountValue = criteria.get(ObjectMetaDataManager.ACCOUNT_FIELD); if ( accountField == null || publicField == null || accountValue == null ) { return; } criteria.remove(ObjectMetaDataManager.ACCOUNT_FIELD); Condition accountCondition = null; if ( accountValue instanceof io.github.ibuildthecloud.gdapi.condition.Condition ) { accountCondition = accountField.in(((io.github.ibuildthecloud.gdapi.condition.Condition)accountValue).getValues()); } else { accountCondition = accountField.eq(accountValue); } criteria.put(Condition.class, publicField.isTrue().or(accountCondition)); } }
protected void addMappingJoins(SelectQuery<?> query, Table<?> toTable, SchemaFactory schemaFactory, String fromType, Table<?> from, String asName, MapRelationship rel) { Table<?> mappingTable = JooqUtils.getTableFromRecordClass(rel.getMappingType()); String mappingType = schemaFactory.getSchemaName(rel.getMappingType()); TableField<?, Object> fieldFrom = JooqUtils.getTableField(getMetaDataManager(), fromType, ObjectMetaDataManager.ID_FIELD); TableField<?, Object> fieldTo = JooqUtils.getTableField(getMetaDataManager(), mappingType, rel.getPropertyName()); TableField<?, Object> fieldRemoved = JooqUtils.getTableField(getMetaDataManager(), mappingType, ObjectMetaDataManager.REMOVED_FIELD); org.jooq.Condition cond = fieldFrom.eq(fieldTo.getTable().field(fieldTo.getName())).and(fieldRemoved == null ? DSL.trueCondition() : fieldRemoved.isNull()); query.addJoin(mappingTable, JoinType.LEFT_OUTER_JOIN, cond); fieldFrom = JooqUtils.getTableField(getMetaDataManager(), mappingType, rel.getOtherRelationship().getPropertyName()); fieldTo = JooqUtils.getTableField(getMetaDataManager(), schemaFactory.getSchemaName(rel.getObjectType()), ObjectMetaDataManager.ID_FIELD); cond = fieldFrom.eq(fieldTo.getTable().asTable(asName).field(fieldTo.getName())); query.addJoin(toTable, JoinType.LEFT_OUTER_JOIN, cond); }
private void addMask(SelectQuery<Record> selectQuery, UUID classifier, UUID classification, TableField<?, UUID> field, ExistentialDomain domain) { if (classifier.equals(WellKnownRelationship.ANY.id())) { if (log.isTraceEnabled()) { log.trace("Match ANY {}", field.getName()); } return; } Condition condition; if (classifier.equals(WellKnownRelationship.SAME.id())) { condition = field.eq(classification); if (log.isTraceEnabled()) { log.trace("Match SAME {}", field.getName()); } } else { condition = field.in(inferenceSubQuery(classifier, classification)); if (log.isTraceEnabled()) { log.trace("Match on inferrred {}", field.getName()); } } condition = condition.or(field.equal(getAnyId(domain))) .or(field.equal(getSameId(domain))) .or(field.equal(getNotApplicable(domain))); selectQuery.addConditions(condition); }
/** * Returns the amount of ins or combs for the given condition. * in == true returns all "ins" / false all "combs" */ private int getVoteAmount(final Condition cond) { return DSL.using(jooqConfig). select(DSL.count()). from(VOTE_TABLE). where(cond).fetchOne(DSL.count()); }
/** * Returns the amount of ins or combs for the given condition. * in == true returns all "ins" / false all "combs" */ private int getVoteAmount(final Condition cond, final boolean in) { return DSL.using(jooqConfig). select(DSL.count()). from(VOTE_TABLE). where(cond). and(VOTE_TABLE.UP.eq(in)).fetchOne(DSL.count()); }
/** * Returns the amount of of comments for the given condition */ private int getCommentsAmount(final Condition cond) { return DSL.using(jooqConfig). select(DSL.count()). from(COMMENT_TABLE). where(cond).fetchOne(DSL.count()); }
static Condition[] columnsEqual(final ColumnPermutation lhs, final ColumnPermutation rhs) { final Condition[] conditions = new Condition[lhs.getColumnIdentifiers().size()]; for (int index = 0; index < lhs.getColumnIdentifiers().size(); ++index) { conditions[index] = toField(lhs.getColumnIdentifiers().get(index)) .eq(toField(rhs.getColumnIdentifiers().get(index))); } return conditions; }
/** * @param keyParser KeyParser containing keys and parsers * @param conditionCreator Condition function of condition that takes values produced by parser * @param <T> To allow to be able to not cast in condition creator function when using less values than other interfaces defined from {@link Value} * @return Filter value that will be dynamically called when building conditions * @throws IllegalArgumentException If KeyParser size is less or equal to 2 */ public static <T extends Value> FilterValue ofN(@NotNull final KeyParser keyParser, @NotNull final Function<T, Condition> conditionCreator) { if (keyParser.size() <= 2) { throw new IllegalArgumentException("KeyParser must be of size 3 or more. Use another builder"); } return new FilterValueImpl(keyParser, conditionCreator); }
AbstractFilterValue(final String key, final Supplier<Condition> conditionSupplier) { this.conditionSupplier = Objects.requireNonNull(conditionSupplier); this.keyParser = KeyParsers.of(key, FilterParser.ofIdentity()::parse); this.conditionCreator = null; this.conditionCreator2 = null; this.throwOnMissingKeysFound = false; }
AbstractFilterValue(final KeyParser keyParser, final Function<Object, Condition> conditionCreator, final boolean throwOnMissingKeysFound) { this.conditionSupplier = null; this.keyParser = Objects.requireNonNull(keyParser); this.conditionCreator = Objects.requireNonNull(conditionCreator); this.conditionCreator2 = null; this.throwOnMissingKeysFound = throwOnMissingKeysFound; }
AbstractFilterValue(final KeyParser keyParser, final BiFunction<Object, Object, Condition> conditionCreator, final boolean throwOnMissingKeysFound) { this.conditionSupplier = null; this.keyParser = Objects.requireNonNull(keyParser); this.conditionCreator = null; this.conditionCreator2 = Objects.requireNonNull(conditionCreator); this.throwOnMissingKeysFound = throwOnMissingKeysFound; }
@NotNull @Override public Condition buildCondition() { if (!isConditionSupplier()) throw new IllegalStateException("Condition supplier is null"); return throwIfConditionIsNull(conditionSupplier.get(), "Cannot return a null condition from a supplier"); }
private static Condition createNTrueCondition(final int n) { if (n < 1) throw new IllegalArgumentException("Cannot have n < 1"); Condition condition = null; for (int i = 0; i < n; i++) { if (condition == null) condition = DSL.trueCondition(); else condition = condition.and(DSL.trueCondition()); } return condition; }
@ParameterizedTest @MethodSource("goodMapConditionAndResult") void buildConditions(final Map<String, String> params, final List<FilterValue> filterValues, final Condition expectedCondition) { filteringJooqImpl1.getFilterValues().addAll(filterValues); final Condition condition = filteringJooqImpl1.buildConditions(params); Assertions.assertEquals(expectedCondition, condition); }