コード例 #1
0
  private void populateBindingSets(
      List<QueryBindingSet> results, Var predVar, Var objVar, Collection<Statement> stmts) {
    if (predVar == null || objVar == null || stmts == null || stmts.size() == 0) return;

    List<QueryBindingSet> copyOf = new ArrayList<QueryBindingSet>(results);

    int i = copyOf.size();
    int j = 0;
    for (Iterator<Statement> iter = stmts.iterator(); iter.hasNext(); ) {
      Statement st = iter.next();
      int k = 0;
      for (QueryBindingSet result : results) {
        if (!result.hasBinding(predVar.getName()) || k >= i) {
          String name = predVar.getName();
          org.openrdf.model.Value val = st.getPredicate();
          addBinding(result, name, val);
        }
        if (!result.hasBinding(objVar.getName()) || k >= i)
          addBinding(result, objVar.getName(), st.getObject());
        k++;
      }

      i = copyOf.size() + j * copyOf.size();
      j++;

      if (iter.hasNext()) {
        // copy results
        for (QueryBindingSet copy : copyOf) {
          results.add(new QueryBindingSet(copy));
        }
      }
    }
  }
コード例 #2
0
  /**
   * Converts the String representation of a {@link Var} back into the object version.
   *
   * @param varString - The {@link Var} represented as a String. (not null)
   * @return A {@link Var} built from the string.
   */
  public static Var toVar(final String varString) {
    checkNotNull(varString);

    if (varString.startsWith("-const-")) {
      // The variable is a constant value.
      final String[] varParts = varString.split(TYPE_DELIM);
      final String name = varParts[0];
      final String valueString = name.substring("-const-".length());

      final String dataTypeString = varParts[1];
      if (dataTypeString.equals(URI_TYPE)) {
        // Handle a URI object.
        final Var var = new Var(name, new URIImpl(valueString));
        var.setAnonymous(true);
        return var;
      } else {
        // Literal value.
        final URI dataType = new URIImpl(dataTypeString);
        final Literal value = new LiteralImpl(valueString, dataType);
        final Var var = new Var(name, value);
        var.setAnonymous(true);
        return var;
      }
    } else {
      // The variable is a named variable.
      return new Var(varString);
    }
  }
コード例 #3
0
 private static String getVarName(ValueExpr v) {
   if (v instanceof Var) {
     Var var = (Var) v;
     if (!var.isConstant()) {
       return var.getName();
     }
   }
   return null;
 }
コード例 #4
0
ファイル: ColumnVar.java プロジェクト: editice/sesame-hbase
 public static ColumnVar createSubj(String alias, Var v, Resource resource) {
   ColumnVar var = new ColumnVar();
   var.alias = alias;
   var.column = "subj";
   var.name = v.getName();
   var.anonymous = v.isAnonymous();
   var.value = resource;
   var.types = ValueTypes.RESOURCE;
   if (resource instanceof RdbmsURI) {
     var.types = ValueTypes.URI;
   }
   return var;
 }
コード例 #5
0
ファイル: ColumnVar.java プロジェクト: editice/sesame-hbase
 public static ColumnVar createObj(String alias, Var v, Value value) {
   ColumnVar var = new ColumnVar();
   var.alias = alias;
   var.column = "obj";
   var.name = v.getName();
   var.anonymous = v.isAnonymous();
   var.value = value;
   var.types = ValueTypes.UNKNOWN;
   if (value instanceof RdbmsURI) {
     var.types = ValueTypes.URI;
   } else if (value instanceof RdbmsResource) {
     var.types = ValueTypes.RESOURCE;
   }
   return var;
 }
コード例 #6
0
ファイル: ColumnVar.java プロジェクト: editice/sesame-hbase
 public static ColumnVar createCtx(String alias, Var v, Resource resource) {
   ColumnVar var = new ColumnVar();
   var.alias = alias;
   var.column = "ctx";
   if (v == null) {
     var.name = "__ctx" + Integer.toHexString(System.identityHashCode(var));
     var.anonymous = true;
     var.hidden = true;
   } else {
     var.name = v.getName();
     var.anonymous = v.isAnonymous();
   }
   var.value = resource;
   var.types = ValueTypes.RESOURCE;
   if (resource instanceof RdbmsURI) {
     var.types = ValueTypes.URI;
   }
   return var;
 }
コード例 #7
0
  protected List<QueryBindingSet> populateBindingSet(
      List<Statement> document, Var subjVar, List<Map.Entry<Var, Var>> predObjVar) {
    // convert document to a multimap
    Multimap<URI, Statement> docMap = ArrayListMultimap.create();
    for (Statement st : document) {
      docMap.put(st.getPredicate(), st);
    }

    List<QueryBindingSet> results = new ArrayList<QueryBindingSet>();
    QueryBindingSet bs0 = new QueryBindingSet(bindings);
    //        QueryBindingSet result = new QueryBindingSet(bindings);

    if (document.size() > 0) {
      Statement stmt = document.get(0);
      if (subjVar != null && !bs0.hasBinding(subjVar.getName())) {
        bs0.addBinding(subjVar.getName(), stmt.getSubject());
      }
    }
    results.add(bs0);

    //        for (Statement st : document) {
    for (Map.Entry<Var, Var> entry : predObjVar) {
      Var predVar = entry.getKey();
      Var objVar = entry.getValue();

      //                if (predVar.hasValue() && !st.getPredicate().equals(predVar.getValue()))
      //                    continue;
      if (predVar == null || !predVar.hasValue()) continue;
      Collection<Statement> predSts = docMap.get((URI) predVar.getValue());

      //            if (predVar != null && !result.hasBinding(predVar.getName()))
      //                result.addBinding(predVar.getName(), st.getPredicate());
      //            if (objVar != null && !result.hasBinding(objVar.getName()))
      //                result.addBinding(objVar.getName(), st.getObject());

      populateBindingSets(results, predVar, objVar, predSts);
    }
    //        }
    return results;
  }
コード例 #8
0
  /**
   * Provides a string representation of an SP which contains info about whether each component
   * (subj, pred, obj) is constant and its data and data type if it is constant.
   *
   * @param sp - The statement pattern to convert. (not null)
   * @return A String representation of the statement pattern that may be used to do triple
   *     matching.
   */
  public static String toStatementPatternString(final StatementPattern sp) {
    checkNotNull(sp);

    final Var subjVar = sp.getSubjectVar();
    String subj = subjVar.getName();
    if (subjVar.isConstant()) {
      subj = subj + TYPE_DELIM + URI_TYPE;
    }

    final Var predVar = sp.getPredicateVar();
    String pred = predVar.getName();
    if (predVar.isConstant()) {
      pred = pred + TYPE_DELIM + URI_TYPE;
    }

    final Var objVar = sp.getObjectVar();
    String obj = objVar.getName();
    if (objVar.isConstant()) {
      final RyaType rt = RdfToRyaConversions.convertValue(objVar.getValue());
      obj = obj + TYPE_DELIM + rt.getDataType().stringValue();
    }

    return subj + DELIM + pred + DELIM + obj;
  }
コード例 #9
0
  @Override
  protected void meetSP(StatementPattern node) throws Exception {
    StatementPattern sp = node.clone();
    final Var predVar = sp.getPredicateVar();

    URI pred = (URI) predVar.getValue();
    String predNamespace = pred.getNamespace();

    final Var objVar = sp.getObjectVar();
    final Var cntxtVar = sp.getContextVar();
    if (objVar != null
        && !RDF.NAMESPACE.equals(predNamespace)
        && !SESAME.NAMESPACE.equals(predNamespace)
        && !RDFS.NAMESPACE.equals(predNamespace)
        && !EXPANDED.equals(cntxtVar)) {

      URI transPropUri = (URI) predVar.getValue();
      if (inferenceEngine.isTransitiveProperty(transPropUri)) {
        node.replaceWith(
            new TransitivePropertySP(
                sp.getSubjectVar(), sp.getPredicateVar(), sp.getObjectVar(), sp.getContextVar()));
      }
    }
  }
コード例 #10
0
 protected BindingSet populateBindingSet(Statement st, List<Map.Entry<Var, Var>> predObjVar) {
   QueryBindingSet result = new QueryBindingSet(bindings);
   for (Map.Entry<Var, Var> entry : predObjVar) {
     Var predVar = entry.getKey();
     Var objVar = entry.getValue();
     if (predVar != null && !result.hasBinding(predVar.getName()))
       result.addBinding(predVar.getName(), st.getPredicate());
     if (objVar != null && !result.hasBinding(objVar.getName()))
       result.addBinding(objVar.getName(), st.getObject());
   }
   return result;
 }
コード例 #11
0
  /**
   * Create a QueryBuilder for creating a describe query
   *
   * @param theVars the variables to be described
   * @param theValues the specific bound URI values to be described
   * @return a describe query builder
   */
  public static QueryBuilder<ParsedGraphQuery> describe(String[] theVars, Resource... theValues) {
    QueryBuilder<ParsedGraphQuery> aBuilder =
        new AbstractQueryBuilder<ParsedGraphQuery>(new ParsedGraphQuery());

    aBuilder.reduced();
    aBuilder.addProjectionVar("descr_subj", "descr_pred", "descr_obj");
    GroupBuilder<?, ?> aGroup = aBuilder.group();

    if (theVars != null) {
      for (String aVar : theVars) {
        Var aVarObj = new Var(aVar);
        aVarObj.setAnonymous(true);

        aGroup
            .filter()
            .or(
                new SameTerm(aVarObj, new Var("descr_subj")),
                new SameTerm(aVarObj, new Var("descr_obj")));
      }
    }

    if (theValues != null) {
      for (Resource aVar : theValues) {
        Var aSubjVar = new Var("descr_subj");
        aSubjVar.setAnonymous(true);

        Var aObjVar = new Var("descr_obj");
        aObjVar.setAnonymous(true);

        aGroup
            .filter()
            .or(
                new SameTerm(new ValueConstant(aVar), aSubjVar),
                new SameTerm(new ValueConstant(aVar), aObjVar));
      }
    }

    aGroup.atom("descr_subj", "descr_pred", "descr_obj");

    return aBuilder;
  }
コード例 #12
0
ファイル: FilterOptimizer.java プロジェクト: apotocki/quetsal
 @Override
 public void meet(Var var) {
   if (var.getValue() == null) vars.add(var.getName());
   super.meet(var);
 }
コード例 #13
0
  @Override
  public void meet(Var node) throws RuntimeException {
    // distinguish between the case where the variable is plain and the variable is bound
    SQLVariable sv = parent.getVariables().get(node.getName());

    if (sv == null) {
      builder.append("NULL");
    } else if (sv.getBindings().size() > 0) {
      // in case the variable is actually an alias for an expression, we evaluate that expression
      // instead, effectively replacing the
      // variable occurrence with its value
      sv.getBindings().get(0).visit(this);
    } else {
      String var = sv.getAlias();

      if (sv.getProjectionType() != ValueType.NODE && sv.getProjectionType() != ValueType.NONE) {
        // in case the variable represents a constructed or bound value instead of a node, we need
        // to
        // use the SQL expression as value; SQL should take care of proper casting...
        // TODO: explicit casting needed?
        builder.append(sv.getExpressions().get(0));
      } else {
        // in case the variable represents an entry from the NODES table (i.e. has been bound to a
        // node
        // in the database, we take the NODES alias and resolve to the correct column according to
        // the
        // operator type
        switch (optypes.peek()) {
          case STRING:
            Preconditions.checkState(var != null, "no alias available for variable");
            builder.append(var).append(".svalue");
            break;
          case INT:
            Preconditions.checkState(var != null, "no alias available for variable");
            builder.append(var).append(".ivalue");
            break;
          case DECIMAL:
          case DOUBLE:
            Preconditions.checkState(var != null, "no alias available for variable");
            builder.append(var).append(".dvalue");
            break;
          case BOOL:
            Preconditions.checkState(var != null, "no alias available for variable");
            builder.append(var).append(".bvalue");
            break;
          case DATE:
            Preconditions.checkState(var != null, "no alias available for variable");
            builder.append(var).append(".tvalue");
            break;
          case TZDATE:
            Preconditions.checkState(var != null, "no alias available for variable");
            builder.append(parent.getDialect().getDateTimeTZ(var));
            break;
          case URI:
            Preconditions.checkState(var != null, "no alias available for variable");
            builder.append(var).append(".svalue");
            break;
          case TERM:
          case NODE:
            if (sv.getExpressions().size() > 0) {
              // this allows us to avoid joins with the nodes table for simple expressions that only
              // need the ID
              builder.append(sv.getExpressions().get(0));
            } else {
              Preconditions.checkState(var != null, "no alias available for variable");
              builder.append(var).append(".id");
            }
            break;
        }
      }
    }
  }
コード例 #14
0
  private TupleExpr buildConstructor(
      TupleExpr bodyExpr,
      TupleExpr constructExpr,
      boolean explicitConstructor,
      boolean distinct,
      boolean reduced) {
    TupleExpr result = bodyExpr;

    // Retrieve all StatementPattern's from the construct expression
    List<StatementPattern> statementPatterns = StatementPatternCollector.process(constructExpr);

    Set<Var> constructVars = getConstructVars(statementPatterns);

    // Note: duplicate elimination is a two-step process. The first step
    // removes duplicates from the set of constructor variables. After this
    // step, any bnodes that need to be generated are added to each solution
    // and these solutions are projected to subject-predicate-object
    // bindings.
    // Finally, the spo-bindings are again filtered for duplicates.
    if (distinct || reduced) {
      // Create projection that removes all bindings that are not used in
      // the
      // constructor
      ProjectionElemList projElemList = new ProjectionElemList();

      for (Var var : constructVars) {
        // Ignore anonymous and constant vars, these will be handled
        // after
        // the distinct
        if (!var.isAnonymous() && !var.hasValue()) {
          projElemList.addElement(new ProjectionElem(var.getName()));
        }
      }

      result = new Projection(result, projElemList);

      // Filter the duplicates from these projected bindings
      if (distinct) {
        result = new Distinct(result);
      } else {
        result = new Reduced(result);
      }
    }

    // Create BNodeGenerator's for all anonymous variables
    Map<Var, ExtensionElem> extElemMap = new HashMap<Var, ExtensionElem>();

    for (Var var : constructVars) {
      if (var.isAnonymous() && !extElemMap.containsKey(var)) {
        ValueExpr valueExpr = null;

        if (var.hasValue()) {
          valueExpr = new ValueConstant(var.getValue());
        } else if (explicitConstructor) {
          // only generate bnodes in case of an explicit constructor
          valueExpr = new BNodeGenerator();
        }

        if (valueExpr != null) {
          extElemMap.put(var, new ExtensionElem(valueExpr, var.getName()));
        }
      }
    }

    if (!extElemMap.isEmpty()) {
      result = new Extension(result, extElemMap.values());
    }

    // Create a Projection for each StatementPattern in the constructor
    List<ProjectionElemList> projections = new ArrayList<ProjectionElemList>();

    for (StatementPattern sp : statementPatterns) {
      ProjectionElemList projElemList = new ProjectionElemList();

      projElemList.addElement(new ProjectionElem(sp.getSubjectVar().getName(), "subject"));
      projElemList.addElement(new ProjectionElem(sp.getPredicateVar().getName(), "predicate"));
      projElemList.addElement(new ProjectionElem(sp.getObjectVar().getName(), "object"));

      projections.add(projElemList);
    }

    if (projections.size() == 1) {
      result = new Projection(result, projections.get(0));

      // Note: no need to apply the second duplicate elimination step if
      // there's just one projection
    } else if (projections.size() > 1) {
      result = new MultiProjection(result, projections);

      if (distinct) {
        // Add another distinct to filter duplicate statements
        result = new Distinct(result);
      } else if (reduced) {
        result = new Reduced(result);
      }
    } else {
      // Empty constructor
      result = new EmptySet();
    }

    return result;
  }
コード例 #15
0
 private String getVariableAlias(Var var) {
   return parent.getVariables().get(var.getName()).getAlias();
 }
コード例 #16
0
 private Value getConstantValue(Var var) {
   return (var != null) ? var.getValue() : null;
 }
コード例 #17
0
 private Resource[] getContexts(Var var) {
   return (var == null || !var.hasValue())
       ? new Resource[0]
       : new Resource[] {(Resource) var.getValue()};
 }