public override SqlObject Visit(SqlSelectClause sqlSelectClause)
 {
     return(SqlSelectClause.Create(
                sqlSelectClause.SelectSpec.Accept(this) as SqlSelectSpec,
                sqlSelectClause.TopSpec?.Accept(this) as SqlTopSpec,
                sqlSelectClause.HasDistinct));
 }
Exemplo n.º 2
0
        /// <summary>
        /// Convert the entire query to a SQL Query.
        /// </summary>
        /// <returns>The corresponding SQL Query.</returns>
        public SqlQuery GetSqlQuery()
        {
            SqlFromClause fromClause;

            if (this.inputQuery != null)
            {
#if SUPPORT_SUBQUERIES
                fromClause = this.CreateSubqueryFromClause();
#else
                throw new DocumentQueryException("SQL subqueries currently not supported");
#endif
            }
            else
            {
                fromClause = this.CreateFrom(inputCollectionExpression: null);
            }

            // Create a SqlSelectClause with the topSpec.
            // If the query is flatten then selectClause may have a topSpec. It should be taken in that case.
            // If the query doesn't have a selectClause, use SELECT v0 where v0 is the input param.
            SqlSelectClause selectClause = this.selectClause;
            if (selectClause == null)
            {
                string parameterName = this.fromParameters.GetInputParameter().Name;
                SqlScalarExpression parameterExpression = SqlPropertyRefScalarExpression.Create(null, SqlIdentifier.Create(parameterName));
                selectClause = this.selectClause = SqlSelectClause.Create(SqlSelectValueSpec.Create(parameterExpression));
            }
            selectClause = SqlSelectClause.Create(selectClause.SelectSpec, selectClause.TopSpec ?? this.topSpec, selectClause.HasDistinct);
            SqlOffsetLimitClause offsetLimitClause = (this.offsetSpec != null) ?
                                                     SqlOffsetLimitClause.Create(this.offsetSpec, this.limitSpec ?? SqlLimitSpec.Create(int.MaxValue)) :
                                                     offsetLimitClause = default(SqlOffsetLimitClause);
            SqlQuery result = SqlQuery.Create(selectClause, fromClause, this.whereClause, this.orderByClause, offsetLimitClause);
            return(result);
        }
        public void SqlArrayScalarExpressionTest()
        {
            CosmosObject tag = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["name"] = CosmosString.Create("asdf")
            });

            CosmosObject tags = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["tags"] = CosmosArray.Create(new List <CosmosElement>()
                {
                    tag
                }),
                ["_rid"] = CosmosString.Create("AYIMAMmFOw8YAAAAAAAAAA==")
            });

            CosmosObject tagsWrapped = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["c"]    = tags,
                ["_rid"] = CosmosString.Create("AYIMAMmFOw8YAAAAAAAAAA==")
            });

            // ARRAY(SELECT VALUE t.name FROM t in c.tags)
            SqlArrayScalarExpression arrayScalarExpression = SqlArrayScalarExpression.Create(
                SqlQuery.Create(
                    SqlSelectClause.Create(
                        SqlSelectValueSpec.Create(
                            TestUtils.CreatePathExpression("t", "name"))),
                    SqlFromClause.Create(
                        SqlArrayIteratorCollectionExpression.Create(
                            SqlIdentifier.Create("t"),
                            SqlInputPathCollection.Create(
                                SqlIdentifier.Create("c"),
                                SqlStringPathExpression.Create(
                                    null,
                                    SqlStringLiteral.Create("tags"))))),
                    whereClause: null,
                    groupByClause: null,
                    orderByClause: null,
                    offsetLimitClause: null));

            CosmosArray tagNames = CosmosArray.Create(new List <CosmosElement>()
            {
                CosmosString.Create("asdf")
            });

            AssertEvaluation(tagNames, arrayScalarExpression, tagsWrapped);
        }
        public override SqlObject VisitSelect_clause([NotNull] sqlParser.Select_clauseContext context)
        {
            SqlSelectSpec sqlSelectSpec = (SqlSelectSpec)this.Visit(context.selection());
            SqlTopSpec    sqlTopSpec;

            if (context.top_spec() != default)
            {
                sqlTopSpec = (SqlTopSpec)this.Visit(context.top_spec());
            }
            else
            {
                sqlTopSpec = default;
            }

            bool distinct = context.K_DISTINCT() != default;

            return(SqlSelectClause.Create(sqlSelectSpec, sqlTopSpec, distinct));
        }
        public void SqlSubqueryScalarExpressionTest()
        {
            SqlLiteralScalarExpression five  = SqlLiteralScalarExpression.Create(SqlNumberLiteral.Create(5));
            SqlLiteralScalarExpression three = SqlLiteralScalarExpression.Create(SqlNumberLiteral.Create(3));

            // (SELECT VALUE 5 + 3)
            SqlSubqueryScalarExpression subqueryScalarExpression = SqlSubqueryScalarExpression.Create(
                SqlQuery.Create(
                    SqlSelectClause.Create(
                        SqlSelectValueSpec.Create(
                            SqlBinaryScalarExpression.Create(
                                SqlBinaryScalarOperatorKind.Add,
                                five,
                                three))),
                    fromClause: null,
                    whereClause: null,
                    groupByClause: null,
                    orderByClause: null,
                    offsetLimitClause: null));

            AssertEvaluation(CosmosNumber64.Create(5 + 3), subqueryScalarExpression);
        }
Exemplo n.º 6
0
        private SqlSelectClause Substitute(SqlSelectClause inputSelectClause, SqlTopSpec topSpec, SqlIdentifier inputParam, SqlSelectClause selectClause)
        {
            SqlSelectSpec selectSpec = inputSelectClause.SelectSpec;

            if (selectClause == null)
            {
                return(selectSpec != null?SqlSelectClause.Create(selectSpec, topSpec, inputSelectClause.HasDistinct) : null);
            }

            if (selectSpec is SqlSelectStarSpec)
            {
                return(SqlSelectClause.Create(selectSpec, topSpec, inputSelectClause.HasDistinct));
            }

            SqlSelectValueSpec selValue = selectSpec as SqlSelectValueSpec;

            if (selValue != null)
            {
                SqlSelectSpec intoSpec = selectClause.SelectSpec;
                if (intoSpec is SqlSelectStarSpec)
                {
                    return(SqlSelectClause.Create(selectSpec, topSpec, selectClause.HasDistinct || inputSelectClause.HasDistinct));
                }

                SqlSelectValueSpec intoSelValue = intoSpec as SqlSelectValueSpec;
                if (intoSelValue != null)
                {
                    SqlScalarExpression replacement         = SqlExpressionManipulation.Substitute(selValue.Expression, inputParam, intoSelValue.Expression);
                    SqlSelectValueSpec  selValueReplacement = SqlSelectValueSpec.Create(replacement);
                    return(SqlSelectClause.Create(selValueReplacement, topSpec, selectClause.HasDistinct || inputSelectClause.HasDistinct));
                }

                throw new DocumentQueryException("Unexpected SQL select clause type: " + intoSpec.Kind);
            }

            throw new DocumentQueryException("Unexpected SQL select clause type: " + selectSpec.Kind);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Flatten subqueries into a single query by substituting their expressions in the current query.
        /// </summary>
        /// <returns>A flattened query.</returns>
        private QueryUnderConstruction Flatten()
        {
            // SELECT fo(y) FROM y IN (SELECT fi(x) FROM x WHERE gi(x)) WHERE go(y)
            // is translated by substituting fi(x) for y in the outer query
            // producing
            // SELECT fo(fi(x)) FROM x WHERE gi(x) AND (go(fi(x))
            if (this.inputQuery == null)
            {
                // we are flat already
                if (this.selectClause == null)
                {
                    // If selectClause doesn't exists, use SELECT v0 where v0 is the input parameter, instead of SELECT *.
                    string parameterName = this.fromParameters.GetInputParameter().Name;
                    SqlScalarExpression parameterExpression = SqlPropertyRefScalarExpression.Create(null, SqlIdentifier.Create(parameterName));
                    this.selectClause = SqlSelectClause.Create(SqlSelectValueSpec.Create(parameterExpression));
                }
                else
                {
                    this.selectClause = SqlSelectClause.Create(this.selectClause.SelectSpec, this.topSpec, this.selectClause.HasDistinct);
                }

                return(this);
            }

            QueryUnderConstruction flatInput   = this.inputQuery.Flatten();
            SqlSelectClause        inputSelect = flatInput.selectClause;
            SqlWhereClause         inputwhere  = flatInput.whereClause;

            // Determine the paramName to be replaced in the current query
            // It should be the top input parameter name which is not binded in this collection.
            // That is because if it has been binded before, it has global scope and should not be replaced.
            string           paramName        = null;
            HashSet <string> inputQueryParams = new HashSet <string>();

            foreach (Binding binding in this.inputQuery.fromParameters.GetBindings())
            {
                inputQueryParams.Add(binding.Parameter.Name);
            }

            foreach (Binding binding in this.fromParameters.GetBindings())
            {
                if (binding.ParameterDefinition == null || inputQueryParams.Contains(binding.Parameter.Name))
                {
                    paramName = binding.Parameter.Name;
                }
            }

            SqlIdentifier         replacement     = SqlIdentifier.Create(paramName);
            SqlSelectClause       composedSelect  = Substitute(inputSelect, inputSelect.TopSpec ?? this.topSpec, replacement, this.selectClause);
            SqlWhereClause        composedWhere   = Substitute(inputSelect.SelectSpec, replacement, this.whereClause);
            SqlOrderbyClause      composedOrderBy = Substitute(inputSelect.SelectSpec, replacement, this.orderByClause);
            SqlWhereClause        and             = QueryUnderConstruction.CombineWithConjunction(inputwhere, composedWhere);
            FromParameterBindings fromParams      = QueryUnderConstruction.CombineInputParameters(flatInput.fromParameters, this.fromParameters);
            SqlOffsetSpec         offsetSpec;
            SqlLimitSpec          limitSpec;

            if (flatInput.offsetSpec != null)
            {
                offsetSpec = flatInput.offsetSpec;
                limitSpec  = flatInput.limitSpec;
            }
            else
            {
                offsetSpec = this.offsetSpec;
                limitSpec  = this.limitSpec;
            }
            QueryUnderConstruction result = new QueryUnderConstruction(this.aliasCreatorFunc)
            {
                selectClause   = composedSelect,
                whereClause    = and,
                inputQuery     = null,
                fromParameters = flatInput.fromParameters,
                orderByClause  = composedOrderBy ?? this.inputQuery.orderByClause,
                offsetSpec     = offsetSpec,
                limitSpec      = limitSpec,
                alias          = new Lazy <ParameterExpression>(() => this.Alias)
            };

            return(result);
        }
        public void SqlExistsScalarExpressionTest()
        {
            CosmosObject tag = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["name"] = CosmosString.Create("asdf")
            });

            CosmosObject tags = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["tags"] = CosmosArray.Create(new List <CosmosElement>()
                {
                    tag
                }),
                ["_rid"] = CosmosString.Create("AYIMAMmFOw8YAAAAAAAAAA==")
            });

            CosmosObject tagsWrapped = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["c"]    = tags,
                ["_rid"] = CosmosString.Create("AYIMAMmFOw8YAAAAAAAAAA==")
            });

            // EXISTS(SELECT VALUE t.name FROM t in c.tags where t.name = "asdf")
            SqlExistsScalarExpression existsScalarExpressionMatched = SqlExistsScalarExpression.Create(
                SqlQuery.Create(
                    SqlSelectClause.Create(
                        SqlSelectValueSpec.Create(
                            TestUtils.CreatePathExpression("t", "name"))),
                    SqlFromClause.Create(
                        SqlArrayIteratorCollectionExpression.Create(
                            SqlIdentifier.Create("t"),
                            SqlInputPathCollection.Create(
                                SqlIdentifier.Create("c"),
                                SqlStringPathExpression.Create(
                                    null,
                                    SqlStringLiteral.Create("tags"))))),
                    SqlWhereClause.Create(
                        SqlBinaryScalarExpression.Create(
                            SqlBinaryScalarOperatorKind.Equal,
                            TestUtils.CreatePathExpression("t", "name"),
                            SqlLiteralScalarExpression.Create(SqlStringLiteral.Create("asdf")))),
                    groupByClause: null,
                    orderByClause: null,
                    offsetLimitClause: null));

            AssertEvaluation(CosmosBoolean.Create(true), existsScalarExpressionMatched, tagsWrapped);

            SqlExistsScalarExpression existsScalarExpressionNotMatched = SqlExistsScalarExpression.Create(
                SqlQuery.Create(
                    SqlSelectClause.Create(
                        SqlSelectValueSpec.Create(
                            TestUtils.CreatePathExpression("t", "name"))),
                    SqlFromClause.Create(
                        SqlArrayIteratorCollectionExpression.Create(
                            SqlIdentifier.Create("t"),
                            SqlInputPathCollection.Create(
                                SqlIdentifier.Create("c"),
                                SqlStringPathExpression.Create(
                                    null,
                                    SqlStringLiteral.Create("tags"))))),
                    SqlWhereClause.Create(
                        SqlBinaryScalarExpression.Create(
                            SqlBinaryScalarOperatorKind.NotEqual,
                            TestUtils.CreatePathExpression("t", "name"),
                            SqlLiteralScalarExpression.Create(SqlStringLiteral.Create("asdf")))),
                    groupByClause: null,
                    orderByClause: null,
                    offsetLimitClause: null));

            AssertEvaluation(CosmosBoolean.Create(false), existsScalarExpressionNotMatched, tagsWrapped);
        }
        public void AliasedCollectionExpressionTest()
        {
            // FROM c
            SqlAliasedCollectionExpression fromC = SqlAliasedCollectionExpression.Create(
                SqlInputPathCollection.Create(
                    SqlIdentifier.Create("c"),
                    relativePath: null),
                alias: null);

            CosmosObject andersenWrapped = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["c"]    = AndersenFamily,
                ["_rid"] = AndersenFamily["_rid"]
            });

            CosmosObject wakeFieldWrapped = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["c"]    = WakefieldFamily,
                ["_rid"] = WakefieldFamily["_rid"]
            });

            AssertEvaluation(new CosmosElement[] { andersenWrapped, wakeFieldWrapped }, fromC, DataSource);

            // FROM c.id
            SqlAliasedCollectionExpression fromCDotId = SqlAliasedCollectionExpression.Create(
                SqlInputPathCollection.Create(
                    SqlIdentifier.Create("c"),
                    SqlIdentifierPathExpression.Create(
                        null,
                        SqlIdentifier.Create("id"))),
                alias: null);

            CosmosObject andersenId = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["id"]   = CosmosString.Create("AndersenFamily"),
                ["_rid"] = AndersenFamily["_rid"]
            });

            CosmosObject wakefieldId = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["id"]   = CosmosString.Create("WakefieldFamily"),
                ["_rid"] = WakefieldFamily["_rid"]
            });

            AssertEvaluation(new CosmosElement[] { andersenId, wakefieldId }, fromCDotId, DataSource);

            // FROM c.id AS familyId
            SqlAliasedCollectionExpression fromCDotIdAsFamilyId = SqlAliasedCollectionExpression.Create(
                SqlInputPathCollection.Create(
                    SqlIdentifier.Create("c"),
                    SqlIdentifierPathExpression.Create(
                        null,
                        SqlIdentifier.Create("id"))),
                SqlIdentifier.Create("familyId"));

            CosmosObject andersenIdAsFamilyId = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["familyId"] = CosmosString.Create("AndersenFamily"),
                ["_rid"]     = AndersenFamily["_rid"]
            });

            CosmosObject wakefieldIdAsFamilyId = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["familyId"] = CosmosString.Create("WakefieldFamily"),
                ["_rid"]     = WakefieldFamily["_rid"]
            });

            AssertEvaluation(new CosmosElement[] { andersenIdAsFamilyId, wakefieldIdAsFamilyId }, fromCDotIdAsFamilyId, DataSource);

            // FROM (SELECT VALUE child["grade"] FROM child IN c.children) grade
            SqlAliasedCollectionExpression fromSubqueryGrades = SqlAliasedCollectionExpression.Create(
                SqlSubqueryCollection.Create(
                    SqlQuery.Create(
                        SqlSelectClause.Create(
                            SqlSelectValueSpec.Create(
                                TestUtils.CreatePathExpression("child", "grade"))),
                        SqlFromClause.Create(
                            SqlArrayIteratorCollectionExpression.Create(
                                SqlIdentifier.Create("child"),
                                SqlInputPathCollection.Create(
                                    SqlIdentifier.Create("c"),
                                    SqlStringPathExpression.Create(
                                        null,
                                        SqlStringLiteral.Create("children"))))),
                        whereClause: null,
                        groupByClause: null,
                        orderByClause: null,
                        offsetLimitClause: null)),
                SqlIdentifier.Create("grade"));

            CosmosObject henrietteWrapped = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["grade"] = CosmosNumber64.Create(5),
                ["_rid"]  = AndersenFamily["_rid"]
            });

            CosmosObject jesseWrapped = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["grade"] = CosmosNumber64.Create(1),
                ["_rid"]  = WakefieldFamily["_rid"]
            });

            CosmosObject lisaWrapped = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["grade"] = CosmosNumber64.Create(8),
                ["_rid"]  = WakefieldFamily["_rid"]
            });

            AssertEvaluation(
                new CosmosElement[]
            {
                henrietteWrapped,
                jesseWrapped,
                lisaWrapped
            },
                fromSubqueryGrades,
                DataSource);
        }