Does not look for redundant joins if not in the LOOSE preservation mode

TODO: consider the case of predicates with multiple non-unique functional dependencies
976731
private ImmutableSet<ExtensionalDataNode> selectNodesToRemove(

            ImmutableSet<Variable> requiredAndCooccuringVariables, ImmutableMap<FunctionalDependency,
            ImmutableCollection<Collection<ExtensionalDataNode>>> constraintNodeMap, AtomPredicate predicate) {

        if (settings.getCardinalityPreservationMode() != LOOSE) {
            return ImmutableSet.of();
        }

        /*
         * Expects that different unique constraints can only remove independent data nodes (-> no conflict)
         *
         * TODO: show why this works
         */
        return constraintNodeMap.entrySet().stream()
                .flatMap(e -> selectNodesToRemovePerConstraint(requiredAndCooccuringVariables, e.getKey(), e.getValue(),
                        predicate))
                .collect(ImmutableCollectors.toSet());
    }
718842
private void appendJoinSQL92NoParen(Join join, StringBuffer where, StringBuffer buf)
    {
        if (join.isOuter)
        {
            buf.append(" LEFT OUTER JOIN ");
        }
        else
        {
            buf.append(" INNER JOIN ");
        }

        buf.append(join.right.getTableAndAlias());
        buf.append(" ON ");
        join.appendJoinEqualities(buf);

        appendTableWithJoins(join.right, where, buf);
    }
1118430
def _compile_update_join_wheres(self, query):
        
        join_wheres = []

        for join in query.joins:
            for clause in join.clauses:
                join_wheres.append(self._compile_join_constraints(clause))

        return " ".join(join_wheres)
1036781
def _merge_model_defined_relation_wheres_to_has_query(self, has_query, relation):
        
        relation_query = relation.get_base_query()

        has_query.merge_wheres(relation_query.wheres, relation_query.get_bindings())

        self._query.add_binding(has_query.get_query().get_bindings(), "where")
620878
private ImmutableMultimap<RelationDefinition, ExtensionalDataNode> extractDataNodeMap(IntermediateQuery query,
                                                                                          InnerJoinNode joinNode) {
        return query.getChildren(joinNode).stream()
                .filter(c -> c instanceof ExtensionalDataNode)
                .map(c -> (ExtensionalDataNode) c)
                .map(c -> Maps.immutableEntry(c.getProjectionAtom().getPredicate().getRelationDefinition(), c))
                .collect(ImmutableCollectors.toMultimap());
    }
1199601
private void checkRelationAndExecuteQuery(String embeddableKey,
            Map<String, List<String>> embeddableToDependentEmbeddables, Map<String, String> queries)
    {
        List<String> dependentEmbeddables = embeddableToDependentEmbeddables.get(embeddableKey);

        if (!dependentEmbeddables.isEmpty())
        {
            for (String dependentEmbeddable : dependentEmbeddables)
            {
                checkRelationAndExecuteQuery(dependentEmbeddable, embeddableToDependentEmbeddables, queries);
            }
        }
        KunderaCoreUtils.printQuery(queries.get(embeddableKey), showQuery);

        try
        {
            cassandra_client.execute_cql3_query(
                    ByteBuffer.wrap(queries.get(embeddableKey).getBytes(Constants.CHARSET_UTF8)), Compression.NONE,
                    ConsistencyLevel.ONE);
        }
        catch (Exception e)
        {
            throw new KunderaException("Error while creating type: " + queries.get(embeddableKey), e);
        }

    }
580285
private boolean existsStrongerInColumn(INode source, INode target) {
        boolean result = false;

        char current = defautlMappings.getRelation(source, target);

        //compare with the other relations in the column
        for (INode i : defautlMappings.getSourceContext().getNodesList()) {
            if (i != source && defautlMappings.getRelation(i, target) != IMappingElement.IDK
                    && isPrecedent(defautlMappings.getRelation(i, target), current)) {
                result = true;
                break;
            }
        }

        return result;
    }
661377
private String constructDuplicatePathSql(SqlgGraph sqlgGraph, List<LinkedList<SchemaTableTree>> subQueryLinkedLists, Set<SchemaTableTree> leftJoinOn) {
        StringBuilder singlePathSql = new StringBuilder("\nFROM (");
        int count = 1;
        SchemaTableTree lastOfPrevious = null;
        for (LinkedList<SchemaTableTree> subQueryLinkedList : subQueryLinkedLists) {
            SchemaTableTree firstOfNext = null;
            boolean last = count == subQueryLinkedLists.size();
            if (!last) {
                //this is to get the next SchemaTable to join to
                LinkedList<SchemaTableTree> nextList = subQueryLinkedLists.get(count);
                firstOfNext = nextList.getFirst();
            }
            SchemaTableTree firstSchemaTableTree = subQueryLinkedList.getFirst();

            String sql;
            if (last) {
                //only the last step must have dropStep as true. As only the outer select needs only an ID in the select
                sql = constructSinglePathSql(sqlgGraph, true, subQueryLinkedList, lastOfPrevious, null, leftJoinOn, false);
            } else {
                sql = constructSinglePathSql(sqlgGraph, true, subQueryLinkedList, lastOfPrevious, firstOfNext);
            }
            singlePathSql.append(sql);
            if (count == 1) {
                singlePathSql.append("\n) a").append(count++).append(" INNER JOIN (");
            } else {
                //join the last with the first
                singlePathSql.append("\n) a").append(count).append(" ON ");
                singlePathSql.append(constructSectionedJoin(sqlgGraph, lastOfPrevious, firstSchemaTableTree, count));
                if (count++ < subQueryLinkedLists.size()) {
                    singlePathSql.append(" INNER JOIN (");
                }
            }
            lastOfPrevious = subQueryLinkedList.getLast();
        }
        singlePathSql.append(constructOuterOrderByClause(sqlgGraph, subQueryLinkedLists));
        String result = "SELECT\n\t" + constructOuterFromClause(subQueryLinkedLists);
        return result + singlePathSql;
    }
655685
private static void checkDuplicates(ImmutableList<SQLPPTriplesMap> mappings)
            throws DuplicateMappingException {

        Set<SQLPPTriplesMap> mappingSet = new HashSet<>(mappings);

        int duplicateCount = mappings.size() - mappingSet.size();

        /**
         * If there are some triplesMaps, finds them
         */
        if (duplicateCount > 0) {
            Set<String> duplicateIds = new HashSet<>();
            int remaining = duplicateCount;
            for (SQLPPTriplesMap mapping : mappings) {
                if (mappingSet.contains(mapping)) {
                    mappingSet.remove(mapping);
                }
                /**
                 * Duplicate
                 */
                else {
                    duplicateIds.add(mapping.getId());
                    if (--remaining == 0)
                        break;
                }
            }
            //TODO: indicate the source
            throw new DuplicateMappingException(String.format("Found %d duplicates in the following ids: %s",
                    duplicateCount, duplicateIds.toString()));
        }
    }
474394
private Set<Predicate> copyPredicatesSet() {
    Set<Predicate> predicatesCopy = Sets.newLinkedHashSet();
    for (Predicate predicate : this.predicates) {
      Predicate copyPredicate = new Predicate();
      copyPredicate.setField(predicate.getField());
      copyPredicate.setOperator(predicate.getOperator());
      copyPredicate.getValues().addAll(predicate.getValues());
      predicatesCopy.add(copyPredicate);
    }
    return predicatesCopy;
  }
1296103
private static boolean isUsingExistingAggregation(
      final Aggregation aggregation,
      final List<Aggregation> existingAggregations
  )
  {
    if (!aggregation.getAggregatorFactories().isEmpty()) {
      return false;
    }

    final Set<String> existingAggregationNames = existingAggregations
        .stream()
        .flatMap(xs -> xs.getAggregatorFactories().stream())
        .map(AggregatorFactory::getName)
        .collect(Collectors.toSet());

    return existingAggregationNames.containsAll(aggregation.getPostAggregator().getDependentFields());
  }
911329
def has_joins(queryset):
    
    for join in six.itervalues(queryset.query.alias_map):
        if join.join_type:
            return True
    return False
995300
private Set<Predicate> copyPredicatesSet() {
    Set<Predicate> predicatesCopy = Sets.newLinkedHashSet();
    for (Predicate predicate : this.predicates) {
      Predicate copyPredicate = new Predicate();
      copyPredicate.setField(predicate.getField());
      copyPredicate.setOperator(predicate.getOperator());
      copyPredicate.setValues(Arrays.copyOf(predicate.getValues(), predicate.getValues().length));
      predicatesCopy.add(copyPredicate);
    }
    return predicatesCopy;
  }
669595
function makerelation (model, relation) {
	let options = {
		as: relation.As,
		foreignKey: relation.key
	};
	let target = exp.databases[inflector.pluralize(relation.Children)];
	if (relation.Rel !== 'manyToMany') {
		exp.databases[model][relation.Rel](target, options);
	} else {
		exp.databases[model].prototype.many2many = exp.databases[model].prototype.many2many || {};
		exp.databases[model].prototype.many2many[relation.Parent] = function (id, id2) {
			if (id && id2) {
				return exp.databases[relation.Children].findcre({
					[`${model}ID`]: id,
					[`${relation.Parent}ID`]: id2
				});
			}
			return exp.databases[relation.Children].find({
				where: {
					[`${model}ID`]: id
				}
			}).then(records => {
				let all = [];
				for (const record of records) {
					all.push(exp.databases[relation.Parent].findById(record[`${relation.Parent}ID`]));
				}
				return Promise.all(all);
			});
		};
	}
}
49430
function _makeJoiner (type) {
	return function (clause, options) {
		if (isQueryizeObject(clause)) {
			if (typeof options !== 'object') throw new Error('You must define join options when joining against a queryize subquery.');

			options = Object.create(options);
			options.table = clause;
			clause = options;
		} else if (typeof clause === 'object') {
			if (isArray(clause)) throw new TypeError('Join clauses can only be strings or object definitions');
			if (!clause.table) throw new Error('You must define a table to join against');
		} else if (typeof options === 'object') {
			options = Object.create(options);
			options.table = clause;
			clause = options;
		}

		if (typeof clause === 'object') {
			clause.type = type;
		} else {
			clause = clause.search(joinTest) > -1 ? clause.replace(joinTest, type + ' JOIN ') : type + ' JOIN ' + clause;
		}

		this.join(clause);

		return this;
	};
}
836483
def check_next_match(self, match, new_relations, subject_graph, one_match):
        """"""
        # only returns true for ecaxtly one set of new_relations from all the
        # ones that are symmetrically equivalent
        if not (self.criteria_sets is None or one_match):
            for check in self.duplicate_checks:
                vertex_a = new_relations.get(check[0])
                vertex_b = new_relations.get(check[1])
                if vertex_a is None and vertex_b is None:
                    continue # if this pair is completely absent in the new
                    # relations, it is either completely in the match or it
                    # is to be matched. So it is either already checked for
                    # symmetry duplicates, or it will be check in future.
                if vertex_a is None:
                    # maybe vertex_a is in the match and vertex_b is the only
                    # one in the new relations. try to get vertex_a from the
                    # match.
                    vertex_a = match.forward.get(check[0])
                    if vertex_a is None:
                        # ok, vertex_a is to be found, don't care about it right
                        # now. it will be checked in future calls.
                        continue
                elif vertex_b is None:
                    # maybe vertex_b is in the match and vertex_a is the only
                    # one in the new relations. try to get vertex_b from the
                    # match.
                    vertex_b = match.forward.get(check[1])
                    if vertex_b is None:
                        # ok, vertex_b is to be found, don't care about it right
                        # now. it will be checked in future calls.
                        continue
                if vertex_a > vertex_b:
                    # Why does this work? The answer is not so easy to explain,
                    # and certainly not easy to find. if vertex_a > vertex_b, it
                    # means that there is a symmetry operation that leads to
                    # an equivalent match where vertex_b < vertex_a. The latter
                    # match is preferred for as much pairs (vertex_a, vertex_b)
                    # as possible without rejecting all possible matches. The
                    # real difficulty is to construct a proper list of
                    # (vertex_a, vertex_b) pairs that will reject all but one
                    # matches. I conjecture that this list contains all the
                    # first two vertices from each normalized symmetry cycle of
                    # the pattern graph. We need a math guy to do the proof. -- Toon
                    return False
            return True
        return True
222026
private void parseRelations(final Object originalEntity, final Object relationEntity,
            final Map<String, Object> relationsMap, final PersistenceDelegator pd, final EntityMetadata metadata,
            boolean lazilyloaded, Map<Object, Object> relationStack)
    {

        for (Relation relation : metadata.getRelations())
        {
            if (relation != null)
            {
                FetchType fetchType = relation.getFetchType();

                if (!lazilyloaded && fetchType.equals(FetchType.LAZY))
                {
                    final Object entityId = PropertyAccessorHelper.getId(relationEntity, metadata);
                    getAssociationBuilder().setProxyRelationObject(relationEntity, relationsMap, metadata, pd,
                            entityId, relation);
                }
                else
                {

                    if (relation.isUnary() && relation.getTargetEntity().isAssignableFrom(originalEntity.getClass()))
                    {
                        Object associationObject = PropertyAccessorHelper.getObject(relationEntity,
                                relation.getProperty());
                        if (relation.getType().equals(ForeignKey.ONE_TO_ONE))
                        {
                            if ((associationObject == null || ProxyHelper.isProxyOrCollection(associationObject)))
                            {
                                PropertyAccessorHelper.set(relationEntity, relation.getProperty(), originalEntity);
                            }
                        }
                        else if (relationsMap != null
                                && relationsMap.containsKey(relation.getJoinColumnName(kunderaMetadata)))
                        {
                            PropertyAccessorHelper.set(relationEntity, relation.getProperty(), originalEntity);
                        }
                    }
                    else
                    {
                        // Here
                        // onRelation(relationEntity, relationsMap, metadata,
                        // pd,
                        // relation, relationType);
                        final Object entityId = PropertyAccessorHelper.getId(relationEntity, metadata);
                        Object relationValue = relationsMap != null ? relationsMap.get(relation
                                .getJoinColumnName(kunderaMetadata)) : null;
                        final EntityMetadata targetEntityMetadata = KunderaMetadataManager.getEntityMetadata(
                                kunderaMetadata, relation.getTargetEntity());
                        List immediateRelations = fetchRelations(relation, metadata, pd, entityId, relationValue,
                                targetEntityMetadata);
                        // Here in case of one-to-many/many-to-one we should
                        // skip
                        // this
                        // relation as it
                        if (immediateRelations != null && !immediateRelations.isEmpty())
                        {
                            for (Object immediateRelation : immediateRelations)
                            {
                                if (immediateRelation != null )
                                {
                                    if (existsInRelationStack(relationStack, immediateRelation, targetEntityMetadata))
                                    {
                                        setRelationToEntity(
                                                relationEntity,
                                                fetchFromRelationStack(relationStack, immediateRelation,
                                                        targetEntityMetadata), relation);

                                    }
                                    else
                                    {
                                        addToRelationStack(relationStack, immediateRelation, targetEntityMetadata);
                                        onParseRelation(relationEntity, pd, targetEntityMetadata, immediateRelation,
                                                relation, lazilyloaded, relationStack);
                                      

                                    }
                                    PersistenceCacheManager.addEntityToPersistenceCache(getEntity(relationEntity), pd,
                                            PropertyAccessorHelper.getId(relationEntity, metadata));
                                }
                            }

                        }
                    }
                }
            }
        }
    }