private static string FormatQueryStatementBody(QueryStatement queryStatement, List <string> properties)
        {
            switch (queryStatement)
            {
            case QueryStatement.InsertQuery:
            {
                var tableFields = string.Join(",", properties);

                var modelFields = $"@{ string.Join(", @", properties) }";
                return($"({tableFields}) values ({modelFields})");
            }

            case QueryStatement.UpdateQuery:
            {
                var updateQuery = new StringBuilder("");
                properties.ForEach(property => { updateQuery.Append($"{property}=@{property}, "); });
                updateQuery.Remove(updateQuery.Length - 2, 2);

                return(updateQuery.ToString());
            }

            default:
                return(string.Empty);
            }
        }
예제 #2
0
        private Statement GetStatement(QueryStatement sq, BindingSet bindings)
        {
            Resource s = GetUniqueBinding(sq.Subject, bindings);
            Resource p = GetUniqueBinding(sq.Predicate, bindings);
            Resource o = GetUniqueBinding(sq.Object, bindings);

            if (s is Literal || p is Literal)
            {
                return(StatementFailed);
            }
            return(new Statement((Entity)s, (Entity)p, o, QueryMeta));
        }
예제 #3
0
        private QueryStatement[] InitBuildNode(ArrayList statements, Hashtable setVars)
        {
            // Get the best statements to consider
            // Because we can consider statements in groups, we need
            // a list of lists.
            QueryStatementComparer comparer = new QueryStatementComparer(setVars, fps, ifps);
            ArrayList considerations        = new ArrayList();

            for (int i = 0; i < statements.Count; i++)
            {
                QueryStatement next = (QueryStatement)statements[i];
                int            comp = 1;
                if (considerations.Count > 0)
                {
                    QueryStatement curcomp = (QueryStatement)((ArrayList)considerations[0])[0];
                    comp = comparer.Compare(curcomp, next);
                }

                if (comp < 0)                 // next is worse than current
                {
                    continue;
                }

                if (comp > 0)                 // clear out worse possibilities
                {
                    considerations.Clear();
                }

                ArrayList group = new ArrayList();
                group.Add(next);
                considerations.Add(group);
            }

            // Pick the group with the most number of statements.
            ArrayList bestgroup = null;

            foreach (ArrayList g in considerations)
            {
                if (bestgroup == null || bestgroup.Count < g.Count)
                {
                    bestgroup = g;
                }
            }

            foreach (QueryStatement qs in bestgroup)
            {
                statements.Remove(qs);
            }

            return((QueryStatement[])bestgroup.ToArray(typeof(QueryStatement)));
        }
예제 #4
0
 public void Set(QueryStatement qs, Statement bs)
 {
     if (qs.Subject.IsVariable)
     {
         Set(qs.Subject.VarIndex, bs.Subject);
     }
     if (qs.Predicate.IsVariable)
     {
         Set(qs.Predicate.VarIndex, bs.Predicate);
     }
     if (qs.Object.IsVariable)
     {
         Set(qs.Object.VarIndex, bs.Object);
     }
 }
예제 #5
0
 public void Clear(QueryStatement qs)
 {
     if (qs.Subject.IsVariable && Bindings[qs.Subject.VarIndex] != null)
     {
         Bindings[qs.Subject.VarIndex].Clear();
     }
     if (qs.Predicate.IsVariable && Bindings[qs.Predicate.VarIndex] != null)
     {
         Bindings[qs.Predicate.VarIndex].Clear();
     }
     if (qs.Object.IsVariable && Bindings[qs.Object.VarIndex] != null)
     {
         Bindings[qs.Object.VarIndex].Clear();
     }
 }
예제 #6
0
        public override Element VisitQueryStatementExp(SqlParser.QueryStatementExpContext context)
        {
            var query = new QueryStatement(CreateParseInfo(context));

            query.Children.Add(Visit(context.s));
            query.Children.Add(Visit(context.f));
            if (context.w != null)
            {
                query.Children.Add(Visit(context.w));
            }
            if (context.l != null)
            {
                query.Children.Add(Visit(context.l));
            }

            return(query);
        }
예제 #7
0
 protected virtual void Visit <TResult>(QueryStatement <TResult> statement)
 {
     Visit(statement.WithStatements);
     Write("SELCT ");
     // .. columns
     if (true /* has from */)
     {
         WriteLine();
         Write("FROM ");
         // .. table name or subquery
     }
     // .. joins
     // .. wheres
     // .. group by
     // .. havings
     // .. ordering
 }
예제 #8
0
 private int Complexity(QueryStatement s)
 {
     if (s.Predicate.IsVariable)
     {
         return(2);
     }
     if ((!s.Subject.IsVariable || setVars.ContainsKey(s.Subject.VarIndex)) &&
         fps.Contains(s.Predicate.Anchor))
     {
         return(0);
     }
     if ((!s.Object.IsVariable || setVars.ContainsKey(s.Object.VarIndex)) &&
         ifps.Contains(s.Predicate.Anchor))
     {
         return(0);
     }
     return(1);
 }
예제 #9
0
            private int NumVars(QueryStatement s)
            {
                int ret = 0;

                if (s.Subject.IsVariable && !setVars.ContainsKey(s.Subject.VarIndex))
                {
                    ret++;
                }
                if (s.Predicate.IsVariable && !setVars.ContainsKey(s.Predicate.VarIndex))
                {
                    ret++;
                }
                if (s.Object.IsVariable && !setVars.ContainsKey(s.Object.VarIndex))
                {
                    ret++;
                }
                return(ret);
            }
예제 #10
0
        public void TestStaticQueries()
        {
            Session         session = new Session(new Dictionary <string, string>(), null, null, null);
            String          query;
            IQueryStatement st;

            query = "SELECT cmis:name FROM cmis:folder";
            st    = new QueryStatement(session, query);
            Assert.AreEqual(query, st.ToQueryString());

            query = "SELECT * FROM cmis:document WHERE cmis:createdBy = \'admin\' AND abc:int = 42";
            st    = new QueryStatement(session, query);
            Assert.AreEqual(query, st.ToQueryString());

            query = "SELECT * FROM cmis:document WHERE abc:test = 'x?z'";
            st    = new QueryStatement(session, query);
            st.SetString(1, "y");
            Assert.AreEqual(query, st.ToQueryString());
        }
예제 #11
0
        private void InitSetStatement(Statement st, ArrayList statements, Hashtable varIndex, bool optional)
        {
            QueryStatement qs = new QueryStatement();

            InitSetStatement(st.Subject, ref qs.Subject, varIndex);
            InitSetStatement(st.Predicate, ref qs.Predicate, varIndex);
            InitSetStatement(st.Object, ref qs.Object, varIndex);

            qs.Optional = optional;

            // If this statement has no variables, add it to a separate list.
            if (!qs.Subject.IsVariable && !qs.Predicate.IsVariable && !qs.Object.IsVariable)
            {
                novariablestatements.Add(st);
            }
            else
            {
                statements.Add(qs);
            }
        }
예제 #12
0
            public int Compare(QueryStatement a, QueryStatement b)
            {
                int optional = a.Optional.CompareTo(b.Optional);

                if (optional != 0)
                {
                    return(optional);
                }

                int numvars = NumVars(a).CompareTo(NumVars(b));

                if (numvars != 0)
                {
                    return(numvars);
                }

                int complexity = Complexity(a).CompareTo(Complexity(b));

                return(complexity);
            }
예제 #13
0
        public static Graph CreateGraph(Story story, QueryStatement query)
        {
            List <string> actors = new List <string>();

            if (query is AfterQueryStatement afterQuery)
            {
                actors = afterQuery.Actions.Select(p => p.Agent).ToList();
            }

            if (query is ExecutableQueryStatement executableQuery)
            {
                actors = executableQuery.Actions.Select(p => p.Agent).ToList();
            }

            if (query is AgentInQueryStatement agentInQuery)
            {
                actors = agentInQuery.Actions.Select(p => p.Agent).Where(p => p != null).ToList();
                if (!string.IsNullOrEmpty(agentInQuery.Agent) && !actors.Contains(agentInQuery.Agent))
                {
                    actors.Add(agentInQuery.Agent);
                }
            }
            return(Graph.CreateGraph(story, actors));
        }
예제 #14
0
			public void Set(QueryStatement qs, Statement bs) {
				if (qs.Subject.IsVariable) Set(qs.Subject.VarIndex, bs.Subject);
				if (qs.Predicate.IsVariable) Set(qs.Predicate.VarIndex, bs.Predicate);
				if (qs.Object.IsVariable) Set(qs.Object.VarIndex, bs.Object);
			}
        public static EntityPropertyProcessorResponse GetFormattedQueryStatementBody <TEntity>(QueryStatement queryStatement, params string[] namesOfPropertiesToBeExcluded)
        {
            var entityPropertyRemovalResponse = namesOfPropertiesToBeExcluded.Any() ?
                                                RemoveProperties(GetEntityProperties(typeof(TEntity).GetProperties()), namesOfPropertiesToBeExcluded) :
                                                new EntityPropertyRemovalResponse {
                Properties = GetEntityProperties(typeof(TEntity).GetProperties())
            };

            if (entityPropertyRemovalResponse.Error != null)
            {
                return new EntityPropertyProcessorResponse {
                           Error = entityPropertyRemovalResponse.Error
                }
            }
            ;

            return(new EntityPropertyProcessorResponse {
                Result = FormatQueryStatementBody(queryStatement, entityPropertyRemovalResponse.Properties)
            });
        }
예제 #16
0
 public BindingEnumerator(QueryStatement qs, QueryResult bindings)
 {
     loops[0] = GetBindings(qs.Subject, bindings);
     loops[1] = GetBindings(qs.Predicate, bindings);
     loops[2] = GetBindings(qs.Object, bindings);
 }
예제 #17
0
			private int Complexity(QueryStatement s) {
				if (s.Predicate.IsVariable) return 2;
				if ((!s.Subject.IsVariable || setVars.ContainsKey(s.Subject.VarIndex))
					&& fps.Contains(s.Predicate.Anchor))
					return 0;
				if ((!s.Object.IsVariable || setVars.ContainsKey(s.Object.VarIndex))
					&& ifps.Contains(s.Predicate.Anchor))
					return 0;
				return 1;
			}
예제 #18
0
			private int NumVars(QueryStatement s) {
				int ret = 0;
				if (s.Subject.IsVariable && !setVars.ContainsKey(s.Subject.VarIndex))
					ret++;
				if (s.Predicate.IsVariable && !setVars.ContainsKey(s.Predicate.VarIndex))
					ret++;
				if (s.Object.IsVariable && !setVars.ContainsKey(s.Object.VarIndex))
					ret++;
				return ret;
			}
예제 #19
0
			public int Compare(QueryStatement a, QueryStatement b) {
				int optional = a.Optional.CompareTo(b.Optional);
				if (optional != 0) return optional;
				
				int numvars = NumVars(a).CompareTo(NumVars(b));
				if (numvars != 0) return numvars;
				
				int complexity = Complexity(a).CompareTo(Complexity(b));
				return complexity;
			}
예제 #20
0
		private void InitSetStatement(Statement st, ArrayList statements, Hashtable varIndex, bool optional) {
			QueryStatement qs = new QueryStatement();
			
			InitSetStatement(st.Subject, ref qs.Subject, varIndex);
			InitSetStatement(st.Predicate, ref qs.Predicate, varIndex);
			InitSetStatement(st.Object, ref qs.Object, varIndex);
			
			qs.Optional = optional;
			
			// If this statement has no variables, add it to a separate list.
			if (!qs.Subject.IsVariable && !qs.Predicate.IsVariable && !qs.Object.IsVariable)
				novariablestatements.Add(st);
			else
				statements.Add(qs);
		}
예제 #21
0
 bool MatchesFilters(Statement s, QueryStatement q, SelectableSource targetModel)
 {
     return(MatchesFilters(s.Subject, q.Subject, targetModel) &&
            MatchesFilters(s.Predicate, q.Predicate, targetModel) &&
            MatchesFilters(s.Object, q.Object, targetModel));
 }
예제 #22
0
        internal void SendModifyView(string schema, string name, string definer, ViewAlgorithm algorithm, ViewSqlSecurity security, ViewCheckOption check, string[] columns, QueryStatement queryStatement)
        {
            var builder = new ModifyView();

            builder.Collection = ExprUtil.BuildCollection(schema, name);
            builder.Definer    = definer;
            builder.Algorithm  = algorithm;
            builder.Security   = security;
            builder.Check      = check;
            if (columns != null && columns.Length > 0)
            {
                foreach (string column in columns)
                {
                    builder.Column.Add(column);
                }
            }
            if (queryStatement != null)
            {
                builder.Stmt = CreateFindMessage(queryStatement.schema,
                                                 queryStatement.collection, queryStatement.isRelational,
                                                 queryStatement.filter, queryStatement.findParams);
            }
            _writer.Write((int)ClientMessages.Types.Type.CrudModifyView, builder);
        }
예제 #23
0
        public void TestWherePlacholder()
        {
            Session         session = new Session(new Dictionary <string, string>(), null, null, null);
            String          query;
            IQueryStatement st;

            // strings
            query = "SELECT * FROM cmis:document WHERE abc:string = ?";
            st    = new QueryStatement(session, query);
            st.SetString(1, "test");
            Assert.AreEqual("SELECT * FROM cmis:document WHERE abc:string = 'test'", st.ToQueryString());

            query = "SELECT * FROM cmis:document WHERE abc:string = ?";
            st    = new QueryStatement(session, query);
            st.SetString(1, "te'st");
            Assert.AreEqual("SELECT * FROM cmis:document WHERE abc:string = 'te\\'st'", st.ToQueryString());

            // likes
            query = "SELECT * FROM cmis:document WHERE abc:string LIKE ?";
            st    = new QueryStatement(session, query);
            st.SetStringLike(1, "%test%");
            Assert.AreEqual("SELECT * FROM cmis:document WHERE abc:string LIKE '%test%'", st.ToQueryString());

            query = "SELECT * FROM cmis:document WHERE abc:string LIKE ?";
            st    = new QueryStatement(session, query);
            st.SetStringLike(1, "\\_test\\%blah\\\\blah");
            Assert.AreEqual("SELECT * FROM cmis:document WHERE abc:string LIKE '\\_test\\%blah\\\\\\\\blah'",
                            st.ToQueryString());

            // contains

            // *, ? and - are treated as text search operators: 1st level escaping:
            // none, 2nd level escaping: none
            // \*, \? and \- are used as literals, 1st level escaping: none, 2nd
            // level escaping: \\*, \\?, \\-
            // ' and " are used as literals, 1st level escaping: \', \", 2nd level
            // escaping: \\\', \\\",
            // \ plus any other character, 1st level escaping \\ plus character, 2nd
            // level: \\\\ plus character

            query = "SELECT * FROM cmis:document WHERE CONTAINS(?)";
            st    = new QueryStatement(session, query);
            st.SetStringContains(1, "John's");
            Assert.AreEqual("SELECT * FROM cmis:document WHERE CONTAINS('John\\\\\\'s')", st.ToQueryString());
            st.SetStringContains(1, "foo -bar");
            Assert.AreEqual("SELECT * FROM cmis:document WHERE CONTAINS('foo -bar')", st.ToQueryString());
            st.SetStringContains(1, "foo*");
            Assert.AreEqual("SELECT * FROM cmis:document WHERE CONTAINS('foo*')", st.ToQueryString());
            st.SetStringContains(1, "foo?");
            Assert.AreEqual("SELECT * FROM cmis:document WHERE CONTAINS('foo?')", st.ToQueryString());
            st.SetStringContains(1, "foo\\-bar");
            Assert.AreEqual("SELECT * FROM cmis:document WHERE CONTAINS('foo\\\\-bar')", st.ToQueryString());
            st.SetStringContains(1, "foo\\*");
            Assert.AreEqual("SELECT * FROM cmis:document WHERE CONTAINS('foo\\\\*')", st.ToQueryString());
            st.SetStringContains(1, "foo\\?");
            Assert.AreEqual("SELECT * FROM cmis:document WHERE CONTAINS('foo\\\\?')", st.ToQueryString());
            st.SetStringContains(1, "\"Cool\"");
            Assert.AreEqual("SELECT * FROM cmis:document WHERE CONTAINS('\\\\\\\"Cool\\\\\\\"')", st.ToQueryString());
            st.SetStringContains(1, "c:\\MyDcuments");
            Assert.AreEqual("SELECT * FROM cmis:document WHERE CONTAINS('c:\\\\MyDcuments')", st.ToQueryString());

            // ids
            query = "SELECT * FROM cmis:document WHERE abc:id = ?";
            st    = new QueryStatement(session, query);
            st.SetId(1, new ObjectId("123"));
            Assert.AreEqual("SELECT * FROM cmis:document WHERE abc:id = '123'", st.ToQueryString());

            // booleans
            query = "SELECT * FROM cmis:document WHERE abc:bool = ?";
            st    = new QueryStatement(session, query);
            st.SetBoolean(1, true);
            Assert.AreEqual("SELECT * FROM cmis:document WHERE abc:bool = TRUE", st.ToQueryString());

            // numbers
            query = "SELECT * FROM cmis:document WHERE abc:int = ? AND abc:int2 = 123";
            st    = new QueryStatement(session, query);
            st.SetInteger(1, 42);
            Assert.AreEqual("SELECT * FROM cmis:document WHERE abc:int = 42 AND abc:int2 = 123", st.ToQueryString());

            // dateTime
            query = "SELECT * FROM cmis:document WHERE abc:dateTime = TIMESTAMP ?";
            DateTime cal = new DateTime(2012, 2, 2, 3, 4, 5, DateTimeKind.Utc);

            st = new QueryStatement(session, query);
            st.SetDateTime(1, cal);
            Assert.AreEqual("SELECT * FROM cmis:document WHERE abc:dateTime = TIMESTAMP '2012-02-02T03:04:05.000Z'",
                            st.ToQueryString());

            st = new QueryStatement(session, query);
            st.SetDateTime(1, DateTimeHelper.ConvertDateTimeToMillis(cal));
            Assert.AreEqual("SELECT * FROM cmis:document WHERE abc:dateTime = TIMESTAMP '2012-02-02T03:04:05.000Z'",
                            st.ToQueryString());

            // dateTime Timestamp
            query = "SELECT * FROM cmis:document WHERE abc:dateTime = ?";

            st = new QueryStatement(session, query);
            st.SetDateTimeTimestamp(1, cal);
            Assert.AreEqual("SELECT * FROM cmis:document WHERE abc:dateTime = TIMESTAMP '2012-02-02T03:04:05.000Z'",
                            st.ToQueryString());

            st = new QueryStatement(session, query);
            st.SetDateTimeTimestamp(1, DateTimeHelper.ConvertDateTimeToMillis(cal));
            Assert.AreEqual("SELECT * FROM cmis:document WHERE abc:dateTime = TIMESTAMP '2012-02-02T03:04:05.000Z'",
                            st.ToQueryString());

            query = "SELECT * FROM cmis:document WHERE abc:dateTime IN (?)";

            st = new QueryStatement(session, query);
            st.SetDateTimeTimestamp(1, cal, cal);
            Assert.AreEqual("SELECT * FROM cmis:document WHERE abc:dateTime "
                            + "IN (TIMESTAMP '2012-02-02T03:04:05.000Z',TIMESTAMP '2012-02-02T03:04:05.000Z')", st.ToQueryString());
        }
예제 #24
0
			public void Clear(QueryStatement qs) {
				if (qs.Subject.IsVariable && Bindings[qs.Subject.VarIndex] != null) Bindings[qs.Subject.VarIndex].Clear();
				if (qs.Predicate.IsVariable && Bindings[qs.Predicate.VarIndex] != null) Bindings[qs.Predicate.VarIndex].Clear();
				if (qs.Object.IsVariable && Bindings[qs.Object.VarIndex] != null) Bindings[qs.Object.VarIndex].Clear();
			}
예제 #25
0
        private bool Query(int groupindex, BindingSet bindings, SelectableSource targetModel)
        {
            QueryStatement[] group = statements[groupindex];

            QueryStatement qs = group[0];

            int numMultiplyBound = IsMultiplyBound(qs.Subject, bindings)
                                   + IsMultiplyBound(qs.Predicate, bindings)
                                   + IsMultiplyBound(qs.Object, bindings);

            if (numMultiplyBound >= 1)
            {
                // If there is one or more multiply-bound variable,
                // then we need to iterate through the permutations
                // of the variables in the statement.

                Debug(qs.ToString() + " Something Multiply Bound");

                MemoryStore matches = new MemoryStore();
                targetModel.Select(
                    new SelectFilter(
                        (Entity[])qs.Subject.GetValues(bindings.Union, true),
                        (Entity[])qs.Predicate.GetValues(bindings.Union, true),
                        qs.Object.GetValues(bindings.Union, false),
                        QueryMeta == null ? null : new Entity[] { QueryMeta }
                        ),
                    new ClearMetaDupCheck(matches));

                Debug("\t" + matches.StatementCount + " Matches");

                if (matches.StatementCount == 0)
                {
                    // This statement doesn't match any of
                    // the existing bindings.  If this was
                    // optional, preserve the bindings.
                    return(qs.Optional);
                }

                // We need to preserve the pairings of
                // the multiply bound variable with the matching
                // statements.

                ArrayList newbindings = new ArrayList();

                if (!qs.Optional)
                {
                    bindings.Union.Clear(qs);
                }

                foreach (QueryResult binding in bindings.Results)
                {
                    // Break apart the permutations in this binding.
                    BindingEnumerator enumer2 = new BindingEnumerator(qs, binding);
                    Entity            s, p;
                    Resource          o;
                    while (enumer2.MoveNext(out s, out p, out o))
                    {
                        // Get the matching statements from the union query
                        Statement   bs           = new Statement(s, p, o);
                        MemoryStore innermatches = matches.Select(bs).Load();

                        // If no matches, the binding didn't match the filter.
                        if (innermatches.StatementCount == 0)
                        {
                            if (qs.Optional)
                            {
                                // Preserve the binding.
                                QueryResult bc = binding.Clone();
                                bc.Set(qs, bs);
                                newbindings.Add(bc);
                                continue;
                            }
                            else
                            {
                                // Toss out the binding.
                                continue;
                            }
                        }

                        for (int si = 0; si < innermatches.StatementCount; si++)
                        {
                            Statement m = innermatches[si];
                            if (!MatchesFilters(m, qs, targetModel))
                            {
                                if (qs.Optional)
                                {
                                    QueryResult bc = binding.Clone();
                                    bc.Set(qs, bs);
                                    newbindings.Add(bc);
                                }
                                continue;
                            }
                            bindings.Union.Add(qs, m);

                            QueryResult r = binding.Clone();
                            r.Set(qs, m);
                            r.StatementMatched[groupindex] = true;
                            newbindings.Add(r);
                        }
                    }
                }

                bindings.Results = newbindings;
            }
            else
            {
                // There are no multiply bound variables, but if
                // there are more than two unbound variables,
                // we need to be sure to preserve the pairings
                // of the matching values.

                int numUnbound = IsUnbound(qs.Subject, bindings)
                                 + IsUnbound(qs.Predicate, bindings)
                                 + IsUnbound(qs.Object, bindings);

                bool sunbound = IsUnbound(qs.Subject, bindings) == 1;
                bool punbound = IsUnbound(qs.Predicate, bindings) == 1;
                bool ounbound = IsUnbound(qs.Object, bindings) == 1;

                Statement s = GetStatement(qs, bindings);

                // If we couldn't get a statement out of this,
                // then if this was not an optional filter,
                // fail.  If this was optional, don't change
                // the bindings any.
                if (s == StatementFailed)
                {
                    return(qs.Optional);
                }

                if (numUnbound == 0)
                {
                    Debug(qs.ToString() + " All bound");

                    // All variables are singly bound already.
                    // We can just test if the statement exists.
                    if (targetModel.Contains(s))
                    {
                        // Mark each binding that it matched this statement.
                        foreach (QueryResult r in bindings.Results)
                        {
                            r.StatementMatched[groupindex] = true;
                        }
                    }
                    else
                    {
                        return(qs.Optional);
                    }
                }
                else if (numUnbound == 1)
                {
                    Debug(qs.ToString() + " 1 Unbound");

                    // There is just one unbound variable.  The others
                    // are not multiply bound, so they must be uniquely
                    // bound (but they may not be bound in all results).
                    // Run a combined select to find all possible values
                    // of the unbound variable at once, and set these to
                    // be the values of the variable for matching results.

                    ResSet      values = new ResSet();
                    MemoryStore ms     = new MemoryStore();
                    targetModel.Select(s, ms);
                    for (int si = 0; si < ms.StatementCount; si++)
                    {
                        Statement match = ms[si];
                        if (!MatchesFilters(match, qs, targetModel))
                        {
                            continue;
                        }
                        if (sunbound)
                        {
                            values.Add(match.Subject);
                        }
                        if (punbound)
                        {
                            values.Add(match.Predicate);
                        }
                        if (ounbound)
                        {
                            values.Add(match.Object);
                        }
                    }

                    Debug("\t" + values.Count + " matches");

                    if (values.Count == 0)
                    {
                        return(qs.Optional);
                    }

                    int varIndex = -1;
                    if (sunbound)
                    {
                        varIndex = qs.Subject.VarIndex;
                    }
                    if (punbound)
                    {
                        varIndex = qs.Predicate.VarIndex;
                    }
                    if (ounbound)
                    {
                        varIndex = qs.Object.VarIndex;
                    }

                    if (bindings.Results.Count == 0)
                    {
                        bindings.Results.Add(new QueryResult(this));
                    }

                    bindings.Union.Bindings[varIndex] = new ResSet();
                    foreach (Resource r in values)
                    {
                        bindings.Union.Bindings[varIndex].Add(r);
                    }

                    foreach (QueryResult r in bindings.Results)
                    {
                        // Check that the bound variables are bound in this result.
                        // If it is bound, it will be bound to the correct resource,
                        // but it might not be bound at all if an optional statement
                        // failed to match -- in which case, don't modify the binding.
                        if (qs.Subject.IsVariable && !sunbound && r.Bindings[qs.Subject.VarIndex] == null)
                        {
                            continue;
                        }
                        if (qs.Predicate.IsVariable && !punbound && r.Bindings[qs.Predicate.VarIndex] == null)
                        {
                            continue;
                        }
                        if (qs.Object.IsVariable && !ounbound && r.Bindings[qs.Object.VarIndex] == null)
                        {
                            continue;
                        }

                        r.Bindings[varIndex]           = values;
                        r.StatementMatched[groupindex] = true;
                    }
                }
                else
                {
                    // There are two or more unbound variables, the
                    // third variable being uniquely bound, if bound.
                    // Keep track of the pairing of unbound variables.

                    if (numUnbound == 3)
                    {
                        throw new QueryExecutionException("Query would select all statements in the store.");
                    }

                    Debug(qs.ToString() + " 2 or 3 Unbound");

                    if (bindings.Results.Count == 0)
                    {
                        bindings.Results.Add(new QueryResult(this));
                    }

                    ArrayList   newbindings = new ArrayList();
                    MemoryStore ms          = new MemoryStore();
                    targetModel.Select(s, ms);
                    for (int si = 0; si < ms.StatementCount; si++)
                    {
                        Statement match = ms[si];
                        if (!MatchesFilters(match, qs, targetModel))
                        {
                            continue;
                        }
                        bindings.Union.Add(qs, match);
                        foreach (QueryResult r in bindings.Results)
                        {
                            if (numUnbound == 2)
                            {
                                // Check that the bound variable is bound in this result.
                                // If it is bound, it will be bound to the correct resource,
                                // but it might not be bound at all if an optional statement
                                // failed to match -- in which case, preserve the binding if
                                // this was an optional statement.
                                bool matches = true;
                                if (qs.Subject.IsVariable && !sunbound && r.Bindings[qs.Subject.VarIndex] == null)
                                {
                                    matches = false;
                                }
                                if (qs.Predicate.IsVariable && !punbound && r.Bindings[qs.Predicate.VarIndex] == null)
                                {
                                    matches = false;
                                }
                                if (qs.Object.IsVariable && !ounbound && r.Bindings[qs.Object.VarIndex] == null)
                                {
                                    matches = false;
                                }
                                if (!matches)
                                {
                                    if (qs.Optional)
                                    {
                                        newbindings.Add(r);
                                    }
                                    continue;
                                }
                            }

                            QueryResult r2 = r.Clone();
                            r2.Add(qs, match);
                            r2.StatementMatched[groupindex] = true;
                            newbindings.Add(r2);
                        }
                    }
                    if (newbindings.Count == 0)
                    {
                        return(qs.Optional);                        // don't clear out bindings if this was optional and it failed
                    }
                    bindings.Results = newbindings;
                }
            }

            return(true);
        }
        public void Visit(QueryStatement statement)
        {
            using (var s = _scope.Push())
            {
                //Visit from to get tables in scope
                if (statement.From != null)
                {
                    VisitChild(statement.From);
                }

                var executedTables = _scope.FetchAllExecutedTablesSameLevel();
                if (executedTables.Length > 0 && statement.Where != null)
                {
                    var rowCount = executedTables.First().Rows.Length;
                    if (rowCount == 0) //even if no rows we still want to validate where variables
                    {
                        Array.ForEach(executedTables, (x) => x.RowIndex = 0);
                        var arg = new QueryPhaseArgs();
                        VisitChild(statement.Where, arg);
                    }
                    else
                    {
                        for (int row = 0; row < rowCount; row++)
                        {
                            Array.ForEach(executedTables, (x) => x.RowIndex = row);
                            var arg = new QueryPhaseArgs();
                            VisitChild(statement.Where, arg);
                            if (!arg.RowResult)
                            {
                                Array.ForEach(executedTables, (x) => x.Rows[x.RowIndex].Match = false);
                            }
                        }
                    }

                    //remove rows that didn't match through all executed tables
                    executedTables = _scope.FetchAllExecutedTablesSameLevel();
                    Array.ForEach(executedTables, (e) =>
                    {
                        var joinedRows = new List <Row>();
                        Array.ForEach(e.Rows, r =>
                        {
                            if (r.Match)
                            {
                                joinedRows.Add(r);
                            }
                        });

                        e.Rows = joinedRows.ToArray();
                    });
                }

                if (statement.Limit != null)
                {
                    VisitChild(statement.Limit);
                }

                var args = new QueryPhaseArgs();
                if (statement.Select != null)
                {
                    VisitChild(statement.Select, args);
                }

                _visitStack.Peek().QueryTable = args.QueryTable;

                if (statement.Bounds.Contains(_editorCursor) && ScopeModel == null)
                {
                    ScopeModel = _scope.BuildScopeModel();
                }
            }
        }
예제 #27
0
			public BindingEnumerator(QueryStatement qs, QueryResult bindings) {
				loops[0] = GetBindings(qs.Subject, bindings);
				loops[1] = GetBindings(qs.Predicate, bindings);
				loops[2] = GetBindings(qs.Object, bindings);
			}
예제 #28
0
 public bool Execute(QueryStatement query, Graph.Graph graph, HistoryStatement history)
 => Execute(query as T, graph, history);
예제 #29
0
		private Statement GetStatement(QueryStatement sq, BindingSet bindings) {
			Resource s = GetUniqueBinding(sq.Subject, bindings);
			Resource p = GetUniqueBinding(sq.Predicate, bindings);
			Resource o = GetUniqueBinding(sq.Object, bindings);
			if (s is Literal || p is Literal) return StatementFailed;
			return new Statement((Entity)s, (Entity)p, o, QueryMeta);
		}
예제 #30
0
파일: DbQuery.cs 프로젝트: aTiKhan/RDO.Net
 private Task EnsureSequentialTempTableCreatedAsync(DbSession dbSession, CancellationToken cancellationToken)
 {
     return(QueryStatement.EnsureSequentialTempTableCreatedAsync(dbSession, cancellationToken));
 }
예제 #31
0
		bool MatchesFilters(Statement s, QueryStatement q, SelectableSource targetModel) {
			return MatchesFilters(s.Subject, q.Subject, targetModel)
				&& MatchesFilters(s.Predicate, q.Predicate, targetModel)
				&& MatchesFilters(s.Object, q.Object, targetModel);
		}