/** * Add the resources of an entity * @param var var representing the entity * @param thing thing containing resource information * @return var pattern with resources */ private static VarPattern hasResources(VarPattern var, Thing thing){ for(Attribute attribute : thing.attributes().collect(Collectors.toSet())){ var = var.has(attribute.type().label(), var().val(attribute.value())); } return var; }
private boolean deleteReferenceInSystemKeyspace(Keyspace keyspace){ try (EmbeddedGraknTx<?> tx = systemKeyspaceSession.transaction(GraknTxType.WRITE)) { AttributeType<String> keyspaceName = tx.getSchemaConcept(KEYSPACE_RESOURCE); Attribute<String> attribute = keyspaceName.attribute(keyspace.getValue()); if(attribute == null) return false; Thing thing = attribute.owner(); if(thing != null) thing.delete(); attribute.delete(); existingKeyspaces.remove(keyspace); tx.commit(); } return true; }
/** * Check if the given {@link Attribute} conforms to the has syntax and structural requirements * @param attribute {@link Attribute} to check * @return true if the {@link Attribute} is target of has relation */ private static boolean isHasResourceResource(Attribute attribute){ AttributeType attributeType = attribute.type(); // TODO: Make sure this is tested boolean plays = attributeType.playing().map(Role::label) .allMatch(c -> c.equals(HAS_VALUE.getLabel(attributeType.label()))); return attribute.owners().findAny().isPresent() && plays; } }
@Override Iterable<? super MatchableConcept> transform(MatchableConcept item) { return item.get().asThing().attributes() .filter(resource -> MatchableConcept.NAME_TYPES.contains(resource.type().label())) .map(MatchableConcept::of) .collect(toSet()); }
private Number getValue(ConceptMap result) { Object value = result.get(varName).asAttribute().value(); if (value instanceof Number) return (Number) value; else throw new RuntimeException("Invalid attempt to compare non-Numbers in Max Aggregate function"); }
/** * If the {@link Attribute} is unique, this method retrieves the Thing that possesses it. * * @return The Thing which is connected to a unique {@link Attribute}. */ @CheckReturnValue @Nullable default Thing owner() { Iterator<Thing> owners = owners().iterator(); if(owners.hasNext()) { return owners.next(); } else { return null; } }
/** * Logs a new {@link Keyspace} to the {@link KeyspaceStore}. * * @param keyspace The new {@link Keyspace} we have just created */ @Override public void addKeyspace(Keyspace keyspace){ if(containsKeyspace(keyspace)) return; try (EmbeddedGraknTx<?> tx = systemKeyspaceSession.transaction(GraknTxType.WRITE)) { AttributeType<String> keyspaceName = tx.getSchemaConcept(KEYSPACE_RESOURCE); if (keyspaceName == null) { throw GraknBackendException.initializationException(keyspace); } Attribute<String> attribute = keyspaceName.create(keyspace.getValue()); if (attribute.owner() == null) { tx.<EntityType>getSchemaConcept(KEYSPACE_ENTITY).create().has(attribute); } tx.commit(); // add to cache existingKeyspaces.add(keyspace); } catch (InvalidKBException e) { throw new RuntimeException("Could not add keyspace [" + keyspace + "] to system graph", e); } }
@Nullable public <T> Entity getEntity(T id, AttributeType<T> rtype){ Attribute<T> iri = rtype.getAttribute(id); Thing inst = iri != null? iri.ownerInstances().findFirst().orElse(null) : null; return inst != null? inst.asEntity() : null; }
/** * Helper class which filters a {@link Stream} of {@link Attribute} to those of a specific set of {@link AttributeType}. * * @param conceptStream The {@link Stream} to filter * @param attributeTypesIds The {@link AttributeType} {@link ConceptId}s to filter to. * @return the filtered stream */ private <X extends Concept> Stream<Attribute<?>> attributes(Stream<X> conceptStream, Set<ConceptId> attributeTypesIds){ Stream<Attribute<?>> attributeStream = conceptStream. filter(concept -> concept.isAttribute() && !this.equals(concept)). map(Concept::asAttribute); if(!attributeTypesIds.isEmpty()){ attributeStream = attributeStream.filter(attribute -> attributeTypesIds.contains(attribute.type().id())); } return attributeStream; }
private Number getValue(ConceptMap result) { Object value = result.get(varName).asAttribute().value(); if (value instanceof Number) return (Number) value; else throw new RuntimeException("Invalid attempt to compare non-Numbers in Min Aggregate function"); }
output.append(colorKeyword("val ")).append(StringUtil.valueToString(concept.asAttribute().value())); } else if (concept.isSchemaConcept()) { SchemaConcept ontoConcept = concept.asSchemaConcept(); String resourceType = colorType(resource.type()); String value = StringUtil.valueToString(resource.value()); output.append(colorKeyword(" has ")).append(resourceType).append(" ").append(value); });
@Override public T unhas(Attribute attribute){ Role roleHasOwner = vertex().tx().getSchemaConcept(Schema.ImplicitType.HAS_OWNER.getLabel(attribute.type().label())); Role roleKeyOwner = vertex().tx().getSchemaConcept(Schema.ImplicitType.KEY_OWNER.getLabel(attribute.type().label())); Role roleHasValue = vertex().tx().getSchemaConcept(Schema.ImplicitType.HAS_VALUE.getLabel(attribute.type().label())); Role roleKeyValue = vertex().tx().getSchemaConcept(Schema.ImplicitType.KEY_VALUE.getLabel(attribute.type().label())); Stream<Relationship> relationships = relationships(filterNulls(roleHasOwner, roleKeyOwner)); relationships.filter(relationship -> { Stream<Thing> rolePlayers = relationship.rolePlayers(filterNulls(roleHasValue, roleKeyValue)); return rolePlayers.anyMatch(rolePlayer -> rolePlayer.equals(attribute)); }).forEach(Concept::delete); return getThis(); }
@Override public List<Value> apply(Stream<? extends ConceptMap> stream) { // initial value is set to null so that we can return null if there is no Answers to consume Number number = stream.map(result -> (Number) result.get(varName).asAttribute().value()).reduce(null, this::add); if (number == null) return Collections.emptyList(); else return Collections.singletonList(new Value(number)); }
@Override public String toString() { if (concept.isAttribute()) { return "hasValue(" + valueToString(concept.asAttribute().value()) + ")"; } else if (concept.isThing()) { Thing thing = concept.asThing(); Stream<Attribute<?>> resources = thing.attributes(); Optional<?> value = resources .filter(resource -> NAME_TYPES.contains(resource.type().label())) .map(Attribute::value).findFirst(); return "instance(" + value.map(StringUtil::valueToString).orElse("") + ") isa " + thing.type().label(); } else if (concept.isType()) { return "type(" + concept.asType().label() + ")"; } else if (concept.isRole()) { return "role(" + concept.asRole().label() + ")"; } else if (concept.isRule()) { return "rule(" + concept.asRule().label() + ")"; } else { throw CommonUtil.unreachableStatement("Unrecognised concept " + concept); } }
/** * Thrown when a {@link Thing} is not allowed to have {@link Attribute} of that {@link AttributeType} */ public static GraknTxOperationException hasNotAllowed(Thing thing, Attribute attribute){ return create(HAS_INVALID.getMessage(thing.type().label(), attribute.type().label())); }
/** * Checks that existing instances match the provided regex. * * @throws GraknTxOperationException when an instance does not match the provided regex * @param regex The regex to check against */ private void checkInstancesMatchRegex(@Nullable String regex){ if(regex != null) { Pattern pattern = Pattern.compile(regex); instances().forEach(resource -> { String value = (String) resource.value(); Matcher matcher = pattern.matcher(value); if(!matcher.matches()){ throw GraknTxOperationException.regexFailure(this, value, regex); } }); } }
@Override public Concept visit(OWLAnnotationAssertionAxiom axiom) { if (! (axiom.getSubject() instanceof OWLNamedIndividual) ) { return null; } Optional<OWLLiteral> value = axiom.getValue().asLiteral(); if (!value.isPresent()) { return null; } @SuppressWarnings("unchecked") AttributeType<String> attributeType = (AttributeType<String>)visit(axiom.getProperty()); Entity entity = migrator.entity((OWLNamedIndividual)axiom.getSubject()); Attribute<String> attribute = attributeType.putAttribute(value.get().getLiteral()); RelationshipType propertyRelation = migrator.relation(axiom.getProperty()); return propertyRelation.addRelationship() .addRolePlayer(migrator.entityRole(entity.type(), attribute.type()), entity) .addRolePlayer(migrator.resourceRole(attribute.type()), attribute); }
@Override public Set<Keyspace> keyspaces() { try (GraknTx graph = systemKeyspaceSession.transaction(GraknTxType.WRITE)) { AttributeType<String> keyspaceName = graph.getSchemaConcept(KEYSPACE_RESOURCE); return graph.<EntityType>getSchemaConcept(KEYSPACE_ENTITY).instances() .flatMap(keyspace -> keyspace.attributes(keyspaceName)) .map(name -> (String) name.value()) .map(Keyspace::of) .collect(Collectors.toSet()); } }
private Relationship attributeRelationship(Attribute attribute, boolean isInferred) { Schema.ImplicitType has = Schema.ImplicitType.HAS; Schema.ImplicitType hasValue = Schema.ImplicitType.HAS_VALUE; Schema.ImplicitType hasOwner = Schema.ImplicitType.HAS_OWNER; //Is this attribute a key to me? if(type().keys().anyMatch(rt -> rt.equals(attribute.type()))){ has = Schema.ImplicitType.KEY; hasValue = Schema.ImplicitType.KEY_VALUE; hasOwner = Schema.ImplicitType.KEY_OWNER; } Label label = attribute.type().label(); RelationshipType hasAttribute = vertex().tx().getSchemaConcept(has.getLabel(label)); Role hasAttributeOwner = vertex().tx().getSchemaConcept(hasOwner.getLabel(label)); Role hasAttributeValue = vertex().tx().getSchemaConcept(hasValue.getLabel(label)); if(hasAttribute == null || hasAttributeOwner == null || hasAttributeValue == null || type().playing().noneMatch(play -> play.equals(hasAttributeOwner))){ throw GraknTxOperationException.hasNotAllowed(this, attribute); } EdgeElement attributeEdge = addEdge(AttributeImpl.from(attribute), Schema.EdgeLabel.ATTRIBUTE); if(isInferred) attributeEdge.property(Schema.EdgeProperty.IS_INFERRED, true); return vertex().tx().factory().buildRelation(attributeEdge, hasAttribute, hasAttributeOwner, hasAttributeValue); }