Beans with different schemaName may have same instance id.

The IN search query is greedy, finding instances that
match any combination of instance id and schemaName. Hence,
the query may find references belonging to wrong schema
so filter those out.
161861
static void filterUnwantedReferences(List<JpaProperty> result, Set<BeanId> query) {
        ListIterator<JpaProperty> it = result.listIterator();
        while (it.hasNext()) {
            // remove property from result that was not part of the query
            JpaProperty found = it.next();
            if (!query.contains(found.getId())) {
                it.remove();
            }
        }
    }
175504
private void matchJoinedFieldsByName(JoinInfo joinInfo, String localColumnName, String joinedColumnName,
			QueryBuilder<?, ?> joinedQueryBuilder) throws SQLException {
		joinInfo.localField = tableInfo.getFieldTypeByColumnName(localColumnName);
		if (joinInfo.localField == null) {
			throw new SQLException("Could not find field in " + tableInfo.getDataClass() + " that has column-name '"
					+ localColumnName + "'");
		}
		joinInfo.remoteField = joinedQueryBuilder.tableInfo.getFieldTypeByColumnName(joinedColumnName);
		if (joinInfo.remoteField == null) {
			throw new SQLException("Could not find field in " + joinedQueryBuilder.tableInfo.getDataClass()
					+ " that has column-name '" + joinedColumnName + "'");
		}
	}
992921
def query(self, name, node):
        
        #log.debug('searching schema for (%s)', name)
        qref = qualify(name, node, node.namespace())
        query = BlindQuery(qref)
        result = query.execute(self.schema)
        return (result, [])
812423
@SuppressWarnings("unchecked")
    protected @Nonnull <T> Collection<BeanDefinition<T>>  findBeanCandidates(@Nonnull Class<T> beanType, @Nullable BeanDefinition<?> filter) {
        ArgumentUtils.requireNonNull("beanType", beanType);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Finding candidate beans for type: {}", beanType);
        }
        // first traverse component definition classes and load candidates

        Collection<BeanDefinitionReference> beanDefinitionsClasses;

        if (indexedTypes.contains(beanType)) {
            beanDefinitionsClasses = beanIndex.get(beanType);
            if (beanDefinitionsClasses == null) {
                beanDefinitionsClasses = Collections.emptyList();
            }
        } else {
            beanDefinitionsClasses = this.beanDefinitionsClasses;
        }

        if (!beanDefinitionsClasses.isEmpty()) {

            Stream<BeanDefinition<T>> candidateStream = beanDefinitionsClasses
                    .stream()
                    .filter(reference -> {
                        if (reference.isPresent()) {
                            Class<?> candidateType = reference.getBeanType();
                            final boolean isCandidate = candidateType != null && (beanType.isAssignableFrom(candidateType) || beanType == candidateType);
                            return isCandidate && reference.isEnabled(this);
                        }
                        return false;
                    })
                    .map(ref -> {
                        BeanDefinition<T> loadedBean;
                        try {
                            loadedBean = ref.load(this);
                        } catch (Throwable e) {
                            throw new BeanContextException("Error loading bean [" + ref.getName() + "]: " + e.getMessage(), e);
                        }
                        return loadedBean;
                    });

            if (filter != null) {
                candidateStream = candidateStream.filter(candidate -> !candidate.equals(filter));
            }
            Set<BeanDefinition<T>> candidates = candidateStream
                    .filter(candidate -> candidate.isEnabled(this))
                    .collect(Collectors.toSet());

            if (!candidates.isEmpty()) {
                filterReplacedBeans(candidates);
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("Resolved bean candidates {} for type: {}", candidates, beanType);
            }
            return candidates;
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No bean candidates found for type: {}", beanType);
            }
            return Collections.emptySet();
        }
    }
985897
def lookupQueryByName( name, dbid=nil  )
      getSchema(dbid) if dbid
      if @queries
         @queries.each_element_with_attribute( "id" ){|q|
            if q.name == "query" and q.elements["qyname"].text.downcase == name.downcase
               return q
            end
         }
      end
      nil
   end
1142443
private boolean isSchemaValid() throws SQLException {
		logger.entering(CLASSNAME, "isSchemaValid");
		Connection conn = getConnectionToDefaultSchema();
		DatabaseMetaData dbmd = conn.getMetaData();
		ResultSet rs = dbmd.getSchemas();
		while(rs.next()) {
			if (schema.equalsIgnoreCase(rs.getString("TABLE_SCHEM")) ) {
				cleanupConnection(conn, rs, null);
				logger.exiting(CLASSNAME, "isSchemaValid", true);
				return true;
			}
		}
		cleanupConnection(conn, rs, null);
		logger.exiting(CLASSNAME, "isSchemaValid", false);
		return false;
	}
327370
def schema_exists(cls, cur, schema_name):
        
        cur.execute("SELECT EXISTS (SELECT schema_name FROM information_schema.schemata WHERE schema_name = '{0}');"
                    .format(schema_name))
        return cur.fetchone()[0]
1144945
static void filterUnwantedReferences(List<JpaRef> result, Collection<BeanId> query) {
        ListIterator<JpaRef> it = result.listIterator();
        while (it.hasNext()) {
            // remove reference from result that was not part of the query
            BeanId found = it.next().getSource();
            if (!query.contains(found)) {
                it.remove();
            }
        }
    }
1347596
function(instances) {
    var queryKey = this.foreignKey;
    var pks = _.map(instances, this.primaryKey);

    if (instances.length === 1) { pks = pks[0]; }
    else { queryKey += '$in'; }

    var where = _.object([[queryKey, pks]]);
    return this._relatedModel.objects.where(where);
  }
23735
def get_id(name=None, tags=None, region=None, key=None,
           keyid=None, profile=None, in_states=None, filters=None):

    '''
    

    '''
    instance_ids = find_instances(name=name, tags=tags, region=region, key=key,
                                  keyid=keyid, profile=profile, in_states=in_states,
                                  filters=filters)
    if instance_ids:
        log.info("Instance ids: %s", " ".join(instance_ids))
        if len(instance_ids) == 1:
            return instance_ids[0]
        else:
            raise CommandExecutionError('Found more than one instance '
                                        'matching the criteria.')
    else:
        log.warning('Could not find instance.')
        return None
169714
protected @Nonnull <T> Collection<BeanDefinition> findBeanCandidatesForInstance(@Nonnull T instance) {
        ArgumentUtils.requireNonNull("instance", instance);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Finding candidate beans for instance: {}", instance);
        }
        Collection<BeanDefinitionReference> beanDefinitionsClasses = this.beanDefinitionsClasses;
        return beanCandidateCache.computeIfAbsent(instance.getClass(), aClass -> {
            // first traverse component definition classes and load candidates

            if (!beanDefinitionsClasses.isEmpty()) {

                List<BeanDefinition> candidates = beanDefinitionsClasses
                        .stream()
                        .filter(reference -> {
                            if (reference.isEnabled(this)) {
                                Class<?> candidateType = reference.getBeanType();

                                return candidateType != null && candidateType.isInstance(instance);
                            } else {
                                return false;
                            }
                        })
                        .map(ref -> ref.load(this))
                        .filter(candidate -> candidate.isEnabled(this))
                        .collect(Collectors.toList());

                if (candidates.size() > 1) {
                    // try narrow to exact type
                    candidates = candidates
                            .stream()
                            .filter(candidate ->
                                    !(candidate instanceof NoInjectionBeanDefinition) &&
                                            candidate.getBeanType() == instance.getClass()
                            )
                            .collect(Collectors.toList());
                    return candidates;
                }
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Resolved bean candidates {} for instance: {}", candidates, instance);
                }
                return candidates;
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("No bean candidates found for instance: {}", instance);
                }
                return Collections.emptySet();
            }
        });

    }
583313
private boolean hasAttributeThatReferences(EntityType candidate, String entityTypeId) {
    Iterable<Attribute> attributes = candidate.getOwnAtomicAttributes();
    return stream(attributes)
        .filter(Attribute::hasRefEntity)
        .map(attribute -> attribute.getRefEntity().getId())
        .anyMatch(entityTypeId::equals);
  }
310930
JMFSchema findSchema(long schemaId) throws MessageStoreException {
    Long storeId = schemaIndex.get(Long.valueOf(schemaId));
    if (storeId != null) {
      AbstractItem item = findById(storeId.longValue());
      return ((SchemaStoreItem)item).getSchema();
    } else
      throw new MessageStoreException("Schema not found in store: " + schemaId);
  }
1207559
def is_common(schema):
    
    if isinstance(schema, StreamSchema):
        return schema.schema() in _SCHEMA_COMMON
    if isinstance(schema, CommonSchema):
        return True
    if isinstance(schema, basestring):
        return is_common(StreamSchema(schema))
    return False
1135401
final public boolean exists() {
		final Model m = Query.one(
				getClass(),
				String.format("SELECT * FROM %s WHERE %s LIMIT 1",
						Utils.getTableName(getClass()),
						Utils.getWhereStatement(this))).get();
		return m != null;
	}
544884
boolean isQueryBean(String owner) {

    int subPackagePos = owner.lastIndexOf("/query/");
    if (subPackagePos > -1) {
      String suffix = owner.substring(subPackagePos);
      if (isQueryBeanSuffix(suffix)) {
        String domainPackage = owner.substring(0, subPackagePos + 1);
        return isQueryBeanPackage(domainPackage);
      }
    }
    return false;
  }
956430
@Override
    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,
            Object columnValue, Class entityClazz)
    {
        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);

        byte[] valueInBytes = HBaseUtils.getBytes(columnValue);
        Filter f = new SingleColumnValueFilter(Bytes.toBytes(tableName), Bytes.toBytes(columnName), CompareOp.EQUAL,
                valueInBytes);
        KeyOnlyFilter keyFilter = new KeyOnlyFilter();
        FilterList filterList = new FilterList(f, keyFilter);
        try
        {
            return handler.scanRowyKeys(filterList, schemaName, tableName, columnName + "_" + columnValue, m
                    .getIdAttribute().getBindableJavaType());
        }
        catch (IOException e)
        {
            log.error("Error while executing findIdsByColumn(), Caused by: .", e);
            throw new KunderaException(e);
        }
    }