01: /*
02: * Copyright Aduna (http://www.aduna-software.com/) (c) 2007.
03: * Copyright James Leigh (c) 2006.
04: *
05: * Licensed under the Aduna BSD-style license.
06: */
07: package org.openrdf.query.algebra.evaluation.impl;
08:
09: import org.openrdf.model.Resource;
10: import org.openrdf.model.Value;
11: import org.openrdf.query.BindingSet;
12: import org.openrdf.query.Dataset;
13: import org.openrdf.query.QueryEvaluationException;
14: import org.openrdf.query.algebra.Compare;
15: import org.openrdf.query.algebra.SameTerm;
16: import org.openrdf.query.algebra.TupleExpr;
17: import org.openrdf.query.algebra.ValueConstant;
18: import org.openrdf.query.algebra.ValueExpr;
19: import org.openrdf.query.algebra.Var;
20: import org.openrdf.query.algebra.Compare.CompareOp;
21: import org.openrdf.query.algebra.evaluation.QueryOptimizer;
22: import org.openrdf.query.algebra.helpers.QueryModelVisitorBase;
23:
24: /**
25: * A query optimizer that replaces {@link Compare} operators with
26: * {@link SameTerm}s, if possible.
27: *
28: * @author Arjohn Kampman
29: */
30: public class CompareOptimizer implements QueryOptimizer {
31:
32: /**
33: * Applies generally applicable optimizations to the supplied query: variable
34: * assignments are inlined.
35: *
36: * @param tupleExpr
37: * @return optimized TupleExpr
38: * @throws QueryEvaluationException
39: */
40: public void optimize(TupleExpr tupleExpr, Dataset dataset,
41: BindingSet bindings) {
42: tupleExpr.visit(new CompareVisitor());
43: }
44:
45: protected class CompareVisitor extends
46: QueryModelVisitorBase<RuntimeException> {
47:
48: @Override
49: public void meet(Compare compare) {
50: super .meet(compare);
51:
52: if (compare.getOperator() == CompareOp.EQ) {
53: ValueExpr leftArg = compare.getLeftArg();
54: ValueExpr rightArg = compare.getRightArg();
55:
56: boolean leftIsVar = isVar(leftArg);
57: boolean rightIsVar = isVar(rightArg);
58: boolean leftIsResource = isResource(leftArg);
59: boolean rightIsResource = isResource(rightArg);
60:
61: if (leftIsVar && rightIsResource || leftIsResource
62: && rightIsVar || leftIsResource
63: && rightIsResource) {
64: SameTerm sameTerm = new SameTerm(leftArg, rightArg);
65: compare.replaceWith(sameTerm);
66: }
67: }
68: }
69:
70: protected boolean isVar(ValueExpr valueExpr) {
71: if (valueExpr instanceof Var) {
72: return true;
73: }
74:
75: return false;
76: }
77:
78: protected boolean isResource(ValueExpr valueExpr) {
79: if (valueExpr instanceof ValueConstant) {
80: Value value = ((ValueConstant) valueExpr).getValue();
81:
82: if (value instanceof Resource) {
83: return true;
84: }
85: }
86:
87: return false;
88: }
89: }
90: }
|