Resolve entity references based on given fetch
774905
@Override
  public Stream<Entity> findAll(Query<Entity> q) {
    Stream<Entity> entities = delegate().findAll(q);
    return resolveEntityReferences(entities, q.getFetch());
  }
615255
private Set<Resource> fetchRelationFromEntity(IncludeRequest request, List<Resource> sourceResources, ResourceField
			relationshipField, boolean allowLookup, boolean fetchRelatedEntity, boolean mustInclude) {
		Set<Resource> loadedResources = new HashSet<>();
		for (Resource sourceResource : sourceResources) {
			ResourceIdentifier id = sourceResource.toIdentifier();

			Object sourceEntity = request.getEntity(id);
			if (sourceEntity != null && !(sourceEntity instanceof Resource)) {

				Object relatedEntity = null;
				if (fetchRelatedEntity) {
					relatedEntity = relationshipField.getAccessor().getValue(sourceEntity);
					if (!allowLookup && Iterable.class.isAssignableFrom(relationshipField.getType()) && relatedEntity == null) {
						// note that single-valued relations are allowed to be null
						throw new InternalServerErrorException(
								id + " relationship field collection '" + relationshipField.getJsonName()
										+ "' can not be null. Either set the relationship as an empty "
										+ Iterable.class.getCanonicalName() + " or use LookupIncludeBehavior.AUTOMATICALLY_ALWAYS");
					}
				}

				// attempt to work with full relationship and fallback to relationshipId where possible
				if (relatedEntity != null) {
					List<Resource> relatedResources =
							request.setupRelation(sourceResource, relationshipField, relatedEntity);
					loadedResources.addAll(relatedResources);
				} else if (relationshipField.hasIdField()) {
					Object relatedEntityID = relationshipField.getIdAccessor().getValue(sourceEntity);
					request.setupRelationId(sourceResource, relationshipField, relatedEntityID);
					if (fetchRelatedEntity && relatedEntityID != null && !allowLookup && mustInclude) {
						throw new IllegalStateException("inconsistent relationship '" + relationshipField.getUnderlyingName()
								+ "' for " + id + ", id "
								+ "set to " + relatedEntityID + ", but related object is null and lookup disabled");
					}
				}
			}
		}
		return loadedResources;
	}
107095
async function fetchAll(connection, query, params){

    // execute query
    const [result] = await _query(connection, query, params);

    // entry found ?
    return result || [];
}
1223768
def resolving(self, ref: str):
        
        new_uri = urlparse.urljoin(self.resolution_scope, ref)
        uri, fragment = urlparse.urldefrag(new_uri)

        if normalize(uri) in self.store:
            schema = self.store[normalize(uri)]
        elif not uri or uri == self.base_uri:
            schema = self.schema
        else:
            schema = resolve_remote(uri, self.handlers)
            if self.cache:
                self.store[normalize(uri)] = schema

        old_base_uri, old_schema = self.base_uri, self.schema
        self.base_uri, self.schema = uri, schema
        try:
            with self.in_scope(uri):
                yield resolve_path(schema, fragment)
        finally:
            self.base_uri, self.schema = old_base_uri, old_schema
552031
@Override
    protected Result<Object> fetchRelated(RegistryEntry entry, Serializable relationId, QueryAdapter queryAdapter) {

        ResultFactory resultFactory = context.getResultFactory();

        String uid = getUID(entry, relationId);
        Object relatedResource = resourceMap.get(uid);
        if (relatedResource != null) {
            return resultFactory.just(relatedResource);
        }
        ResourceInformation resourceInformation = entry.getResourceInformation();
        Class<?> resourceClass = resourceInformation.getResourceClass();
        return resultFactory.just(proxyFactory.createResourceProxy(resourceClass, relationId));
    }
1017603
public static WstxInputSource resolveEntityUsing
        (WstxInputSource refCtxt, String entityName,
         String publicId, String systemId,
         XMLResolver resolver, ReaderConfig cfg, int xmlVersion)
        throws IOException, XMLStreamException
    {
        URL ctxt = (refCtxt == null) ? null : refCtxt.getSource();
        if (ctxt == null) {
            ctxt = URLUtil.urlFromCurrentDir();
        }
        Object source = resolver.resolveEntity(publicId, systemId, ctxt.toExternalForm(), entityName);
        return (source == null) ? null : sourceFrom(refCtxt, cfg, entityName, xmlVersion, source);
    }
1160531
function fetchExternals(request, body) {

    var includes = parseIncludes(request);
    var user = request.user;
    var requestsByType = groupIncludes(includes, body);

    return when.all(_.map(requestsByType, function(requestData, ancestorType) {
        var ids = _.uniq(requestData.ids);
        return fetchAncestor(ancestorType, ids, _.compact(_.map(requestData.includes, function(i) { return _.rest(i).join("."); })).join(","), request)
          .then(function(response){
            return response;
          })
          .then(function(data) {
            _.each(requestData.includes, function(split) {
              mergeAncestorData(body, split, ancestorType, data);
            });
          })
          .catch(function(err) { console.trace(err.stack || err); });
      })).then(function() {
        return body;
      });
  }
757409
@Override
  public InputSource resolveEntity(String publicId, String systemId)
  {
    String r = map.get(publicId);
    return r == null ? null : new InputSource(Resources.stream(r));
  }
938634
function resolveRelated(np) {

    var fkNames = np.foreignKeyNames;
    if (fkNames.length === 0) return;

    var parentEntityType = np.parentType;
    var fkProps = fkNames.map(function (fkName) {
      return parentEntityType.getDataProperty(fkName);
    });
    var fkPropCollection = parentEntityType.foreignKeyProperties;

    fkProps.forEach(function (dp) {
      __arrayAddItemUnique(fkPropCollection, dp);
      dp.relatedNavigationProperty = np;
      // now update the inverse
      __arrayAddItemUnique(np.entityType.inverseForeignKeyProperties, dp);
      if (np.relatedDataProperties) {
        __arrayAddItemUnique(np.relatedDataProperties, dp);
      } else {
        np.relatedDataProperties = [dp];
      }
    });
  }
1170291
function resolveRef(swagger, ref) {
  if (ref.indexOf('#/') != 0) {
    console.error('Resolved references must start with #/. Current: ' + ref);
    process.exit(1);
  }
  var parts = ref.substr(2).split('/');
  var result = swagger;
  for (var i = 0; i < parts.length; i++) {
    var part = parts[i];
    result = result[part];
  }
  return result === swagger ? {} : result;
}
1125614
function lookupInDatabase(db) {
    return new Promise((resolve, reject) => {
      var store = db.transaction([storeName]).objectStore(storeName);
      var request = store.get(url);
      request.onerror = reject.bind(null, `Error getting wasm module ${url}`);
      request.onsuccess = event => {
        if (request.result)
          resolve(request.result);
        else
          reject(`Module ${url} was not found in wasm cache`);
      }
    });
  }
832994
@Override
  public Entity findOne(Query<Entity> q) {
    Entity entity = delegate().findOne(q);
    return entity != null ? resolveEntityReferences(entity, q.getFetch()) : null;
  }
1103578
async function retrieveEntityByAttribute(
    entitySet,
    componentID,
    attribute,
    value
) {
    // Log.debug('[retrieveEntityByAttribute]', componentID, 'where', attribute, 'equals', value);
    const query = Q => [
        Q.all(componentID).where(Q.attr(attribute).equals(value)),
        Q.limit(1)
    ];

    if (entitySet.isAsync) {
        const existing = await entitySet.query(query, { debug: false });

        // Log.debug('[retrieveEntityByAttribute]', entityToString( existing));
        if (existing.size() === 1) {
            return existing.at(0);
        }

        return null;
    } else {
        return Promise.resolve(true).then(() => {
            const existing = entitySet.query(query);
            // Log.debug('[retrieveEntityByAttribute]', 'query result', existing.size(), entityToString(existing), componentID, attribute, value );
            if (existing.size() === 1) {
                return existing.at(0);
            }
            return null;
        });
    }
}
1367157
public boolean hasCollectionFetch()
	{
		if (fetches != null)
			for (String fetch : fetches)
			{
				QEntity parent = entity;

				final String[] parts = StringUtils.split(fetch, '.');

				for (int i = 0; i < parts.length; i++)
				{
					// If this is a fully supported relation then continue checking
					if (parent.hasRelation(parts[i]))
					{
						final QRelation relation = parent.getRelation(parts[i]);

						parent = relation.getEntity();

						if (relation.isCollection())
						{
							if (log.isTraceEnabled())
								log.trace("Encountered fetch " +
								          fetch +
								          ". This resolves to " +
								          relation +
								          " which is a collection");

							return true;
						}
					}
					// This covers partially-supported things like Map and other basic collections that don't have a QRelation description
					else if (parent.hasNonEntityRelation(parts[i]))
					{
						if (parent.isNonEntityRelationCollection(parts[i]))
							return true;
					}
					else
					{
						log.warn("Encountered relation " +
						         parts[i] +
						         " on " +
						         parent.getName() +
						         " as part of path " +
						         fetch +
						         ". Assuming QEntity simply does not know this relation. Assuming worst case scenario (collection join is involved)");
						return true;
					}
				}
			}

		return false;
	}
792680
private function fetchReferences() {
        $qry = "SELECT i.CONSTRAINT_NAME as constraintName, i.CONSTRAINT_TYPE as constraintType,
			j.COLUMN_NAME as columnName, j.REFERENCED_TABLE_SCHEMA as refDB, j.REFERENCED_TABLE_NAME as refTable,
			j.REFERENCED_COLUMN_NAME as refColumn, k.UPDATE_RULE as onUpdate, k.DELETE_RULE as onDelete" .
                " FROM information_schema.TABLE_CONSTRAINTS i" .
                " LEFT JOIN information_schema.KEY_COLUMN_USAGE j
                    ON i.CONSTRAINT_NAME = j.CONSTRAINT_NAME AND j.TABLE_SCHEMA = '" . $this->connection->getDBName() . "'
			AND j.TABLE_NAME = '" . $this->name . "'" .
                " LEFT JOIN information_schema.REFERENTIAL_CONSTRAINTS k
                    ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME AND j.CONSTRAINT_SCHEMA = k.CONSTRAINT_SCHEMA
			AND k.TABLE_NAME = '" . $this->name . "'" .
                " WHERE i.TABLE_SCHEMA = '" . $this->connection->getDBName() . "'
								AND i.TABLE_NAME = '" . $this->name . "'";

        $define = $this->connection->doPrepare($qry);
        if (is_bool($define)) return;

        foreach ($define as $info) {
            if (isset($info['constraintType']) && $info['constraintType'] === 'PRIMARY KEY') {
                if (isset($info['columnName']))
                        $this->primaryKey = $info['columnName'];
            } else if ($info['refTable']) {
                if (isset($info['constraintType']))
                        unset($info['constraintType']);
                if (isset($info['columnName'])) {
                    $name = $info['columnName'];
                    unset($info['columnName']);
                }
                $this->references[$name] = $info;
            }
        }
    }
428878
@Override
  public void forEachBatched(Fetch fetch, Consumer<List<Entity>> consumer, int batchSize) {
    delegate()
        .forEachBatched(
            fetch,
            entities -> {
              List<Entity> resolvedEntities =
                  resolveEntityReferences(entities.stream(), fetch).collect(Collectors.toList());
              consumer.accept(resolvedEntities);
            },
            batchSize);
  }
864073
function resolveSchemaRefs(data, lookup) {
  if (!data || dataCache.has(data)) return data

  if (Array.isArray(data)) {
    return data.map(item => resolveSchemaRefs(item, lookup))
  } else if (typeof data === 'object') {
    if (data.$ref) {
      const resolved = resolveSchemaRef(data.$ref, lookup)
      delete data.$ref
      data = Object.assign({}, resolved, data)
    }
    dataCache.add(data)

    for (let name in data) {
      data[name] = resolveSchemaRefs(data[name], lookup)
    }
  }
  return data
}