public void TestMultiExpression() { var translator = new QueryTranslator(); Expression<Func<TestRecord, bool>> expression = x => x.Col1 == 1 && x.Col2 == 2.3; string result = translator.Translate(expression); Assert.True(result == "((Col1 = 1) AND (Col2 = 2.3))"); }
public void TestAndOrExpression() { var translator = new QueryTranslator(); Expression<Func<TestRecord, bool>> expression = x => x.Col1 == 1 && x.Col2 == 2.3 || x.Col3 == "test"; string result = translator.Translate(expression); Assert.True(result == "(((Col1 = 1) AND (Col2 = 2.3)) OR (Col3 = 'test'))"); }
public void TestSingleExpression() { var translator = new QueryTranslator(); Expression<Func<TestRecord, bool>> expression = x => x.Col1 == 1; string result = translator.Translate(expression); Assert.True(result == "(Col1 = 1)"); }
public void TestContainsExpression() { var translator = new QueryTranslator(); var items = Enumerable.Range(1, 5).Cast<int?>(); Expression<Func<TestRecord, bool>> expression = x => items.Contains(x.Col1); string result = translator.Translate(expression); Assert.True(result == "(Col1 IN(1, 2, 3, 4, 5))"); }
/// <summary> /// /// </summary> /// <param name="q"></param> /// <param name="token"></param> protected override void AppendToken( QueryTranslator q, string token ) { // a String.Empty can get passed in here. If that occurs // then don't create a new SqlString for it - just ignore // it since it adds nothing to the sql being generated. if( token != null && token.Length > 0 ) { q.AppendHavingToken( token ); } }
/// <summary> /// /// </summary> /// <param name="q"></param> public override void End(QueryTranslator q) { if (CurrentProperty != null && !q.IsShallowQuery) { // "finish off" the join Token(".", q); Token(null, q); } base.End(q); }
public void Default_Rank() { using (var provider = new LinqCloudSearchClient()) { var query = provider.Query<TestDocument>(); var translator = new QueryTranslator(provider); var result = translator.Translate(query.Expression); Assert.AreEqual(0, result.SearchRequest.Rank.Count); } }
public void OrderByDescending_To_Rank() { using (var provider = new LinqCloudSearchClient()) { var query = provider.Query<TestDocument>() .OrderByDescending(td => td.SomeString); var translator = new QueryTranslator(provider); var result = translator.Translate(query.Expression); Assert.AreEqual("-some_string", result.SearchRequest.Rank.ToQueryStringParameterValue()); } }
public void Default_To_Return_All_Fields() { using (var provider = new LinqCloudSearchClient()) { var query = provider.Query<TestDocument>(); var translator = new QueryTranslator(provider); var result = translator.Translate(query.Expression); var actualFields = result.SearchRequest.ReturnFields; CollectionAssert.AreEquivalent(new string[] { "some_integer", "some_string" }, actualFields.ToArray()); } }
public void Select_OrderBy() { using (var provider = new LinqCloudSearchClient()) { var query = provider.Query<TestDocument>() .Select(td => td.SomeInteger) .OrderByDescending(p => p); var translator = new QueryTranslator(provider); var result = translator.Translate(query.Expression); CollectionAssert.AreEquivalent(new string[] { "some_integer" }, result.SearchRequest.ReturnFields.ToArray()); Assert.AreEqual("-some_integer", result.SearchRequest.Rank.ToQueryStringParameterValue()); } }
public void Test_Content_Search_With_TagFilter_Translate() { var opqs = new QueryTranslator(); var sp = new ContentSearchParameters { From = new DateTime(1971, 2, 20), Query = "prince", TagFilter = new List<string> {"music/music", "culture/culture"} }; var result = new Uri(opqs.Translate(sp)); Assert.IsTrue(result.Query.Contains("q=prince")); Assert.IsTrue(result.Query.Contains("from-date=1971-02-20")); Assert.IsTrue(result.Query.Contains("tag=music/music,culture/culture")); Assert.IsTrue(result.Query.Contains("api-key=" + _key)); }
public void Test_ContentSearch_Translate() { var sp = new ContentSearchParameters { From = new DateTime(1971, 2, 20), Query = "cristiano ronaldo" }; var opqs = new QueryTranslator(); var result = new Uri(opqs.Translate(sp)); Assert.AreEqual(_baseUrl.Host, result.Host); Assert.IsTrue(result.Query.Contains("q=cristiano%20ronaldo")); Assert.IsTrue(result.Query.Contains("from-date=1971-02-20")); Assert.IsTrue(result.Query.Contains("api-key=" + _key)); }
public void Simple_Query_Translate() { var container = new NinjectContainer(); var map = container.Resolve<IMappingManager>(); var mapper = new PersonMap(); mapper.ExecuteMapping(); map.Register(mapper.MappedType, mapper); var query = new Query<Person>(); query.Where(x => x.Name).Equal("Alaor").And(x => x.Age).GreaterThan(18).And(x => x.Id).NotEqual(0); var translator = new QueryTranslator(map); var result = translator.Translate(query); result.SqlText.Trim().ToUpper().Should().Be("NAME = @PARAMETER_0 AND AGE > @PARAMETER_1 AND ID <> @PARAMETER_2"); result.Parameters.Count.Should().Be(3); }
public void Test_Content_Search_With_ShowTags_and_ShowFields_Translate() { var opqs = new QueryTranslator(); var sp = new ContentSearchParameters { From = new DateTime(1971, 2, 20), Query = "prince", ShowTags = new List<string>{"all"}, ShowFields= new List<string>{"body,star-rating"} }; var result = new Uri(opqs.Translate(sp)); Assert.IsTrue(result.Query.Contains("q=prince")); Assert.IsTrue(result.Query.Contains("from-date=1971-02-20")); Assert.IsTrue(result.Query.Contains("show-tags=all")); Assert.IsTrue(result.Query.Contains("show-fields=body,star-rating")); Assert.IsTrue(result.Query.Contains("api-key=" + _key)); }
public CompilerResults compileFromCompilationUnits(CompilerParameters parameters, CompilationUnitNode[] compilationUnits) { var results = new CompilerResults(); this.context = new CompilerContext(parameters, results); this.statementValidator = new StatementValidator(this.context); this.expressionValidator = new ExpressionValidator(this.context); this.statementValidator.ExpressionValidator = this.expressionValidator; this.expressionValidator.StatementValidator = this.statementValidator; this.reachabilityChecker = new ReachabilityChecker(context); this.assignmentChecker = new AssignmentChecker(context); this.bytecodeGenerator = new BytecodeGenerator(context); foreach (var cu in compilationUnits) { context.CompilationUnits.add(cu); } doCompile(); this.context = null; this.statementValidator = null; this.expressionValidator = null; this.reachabilityChecker = null; this.assignmentChecker = null; this.queryTranslator = null; this.documentationBuilder = null; if (parameters.ProgressTracker != null) { parameters.ProgressTracker.compilationFinished(); } return results; }
private string GetElementName(PathExpressionParser.CollectionElement element, QueryTranslator q) { string name; if (element.IsOneToMany) { name = element.Alias; } else { IType type = element.Type; System.Type clazz; if (type.IsEntityType) { //ie. a many-to-many clazz = (( EntityType )type).AssociatedClass; name = pathExpressionParser.ContinueFromManyToMany(clazz, element.ElementColumns, q); } else { throw new QueryException("illegally dereferenced collection element"); } } return(name); }
/// <summary> /// /// </summary> /// <param name="token"></param> /// <param name="q"></param> public void Token(string token, QueryTranslator q) { string lcToken = token.ToLower(System.Globalization.CultureInfo.InvariantCulture); //Cope with [,] if (token.Equals("[") && !expectingPathContinuation) { expectingPathContinuation = false; if (expectingIndex == 0) { throw new QueryException("unexpected ["); } return; } else if (token.Equals("]")) { expectingIndex--; expectingPathContinuation = true; return; } //Cope with a continued path expression (ie. ].baz) if (expectingPathContinuation) { if (ContinuePathExpression(token, q)) { return; } } //Cope with a subselect if (!inSubselect && (lcToken.Equals("select") || lcToken.Equals("from"))) { inSubselect = true; subselect = new StringBuilder(20); } if (inSubselect && token.Equals(StringHelper.ClosedParen)) { bracketsSinceSelect--; if (bracketsSinceSelect == -1) { QueryTranslator subq = new QueryTranslator(subselect.ToString()); try { subq.Compile(q); } catch (MappingException me) { throw new QueryException("MappingException occurred compiling subquery", me); } AppendToken(q, subq.SqlString); inSubselect = false; bracketsSinceSelect = 0; } } if (inSubselect) { if (token.Equals(StringHelper.OpenParen)) { bracketsSinceSelect++; } subselect.Append(token).Append(' '); return; } //Cope with special cases of AND, NOT, () SpecialCasesBefore(lcToken); //Close extra brackets we opened if (!betweenSpecialCase && expressionTerminators.Contains(lcToken)) { CloseExpression(q, lcToken); } //take note when this is a boolean expression if (booleanOperators.Contains(lcToken)) { booleanTests.RemoveAt(booleanTests.Count - 1); booleanTests.Add(true); } if (lcToken.Equals("not")) { nots[nots.Count - 1] = !(( bool )nots[nots.Count - 1]); negated = !negated; return; //NOTE: early return } //process a token, mapping OO path expressions to SQL expressions DoToken(token, q); //Open any extra brackets we might need. if (!betweenSpecialCase && expressionOpeners.Contains(lcToken)) { OpenExpression(q, lcToken); } //Cope with special cases of AND, NOT, ) SpecialCasesAfter(lcToken); }
/// <summary> /// /// </summary> /// <param name="q"></param> public void Start(QueryTranslator q) { Token(StringHelper.OpenParen, q); }
private QueryParameters GetFilteredQueryParameters(QueryParameters queryParameters, QueryTranslator translator) { QueryParameters filteredQueryParameters = queryParameters; IDictionary namedParameters = new Hashtable(queryParameters.NamedParameters); filteredQueryParameters.NamedParameters.Clear(); foreach (string paramName in translator.GetParameterTranslations().GetNamedParameterNames()) { if (namedParameters.Contains(paramName)) { filteredQueryParameters.NamedParameters.Add(paramName, namedParameters[paramName]); } } return filteredQueryParameters; }
public virtual QueryLinguist CreateLinguist(QueryTranslator translator) { return new QueryLinguist(this, translator); }
/// <summary> /// Aggregate Function /// </summary> /// <typeparam name="T">data type</typeparam> /// <param name="server">database server</param> /// <param name="cmd">command</param> /// <returns></returns> async Task <T> AggregateFunctionAsync <T>(ServerInfo server, ICommand cmd) { if (cmd.Query == null) { throw new EZNEWException("ICommand.Query is null"); } #region query object translate IQueryTranslator translator = QueryTranslator.GetTranslator(server); var tranResult = translator.Translate(cmd.Query); #endregion #region execute StringBuilder cmdText = new StringBuilder(); string joinScript = tranResult.AllowJoin ? tranResult.JoinScript : string.Empty; switch (cmd.Query.QueryType) { case QueryCommandType.Text: cmdText.Append(tranResult.ConditionString); break; case QueryCommandType.QueryObject: default: string funcName = GetAggregateFunctionName(cmd.Operate); if (funcName.IsNullOrEmpty()) { return(default(T)); } #region field EntityField field = null; if (AggregateOperateMustNeedField(cmd.Operate)) { if (cmd.Query?.QueryFields.IsNullOrEmpty() ?? true) { throw new EZNEWException(string.Format("You must specify the field to perform for the {0} operation", funcName)); } else { field = DataManager.GetField(ServerType.SQLServer, cmd.EntityType, cmd.Query.QueryFields[0]); } } else { field = DataManager.GetDefaultField(ServerType.SQLServer, cmd.EntityType); } #endregion string objectName = DataManager.GetEntityObjectName(ServerType.SQLServer, cmd.EntityType, cmd.ObjectName); cmdText.AppendFormat("{4}SELECT {0}({1}) FROM [{2}] AS {3}{5}" , funcName , FormatField(translator.ObjectPetName, field) , objectName , translator.ObjectPetName , tranResult.PreScript , joinScript); if (!tranResult.ConditionString.IsNullOrEmpty()) { cmdText.AppendFormat(" WHERE {0}", tranResult.ConditionString); } if (!tranResult.OrderString.IsNullOrEmpty()) { cmdText.AppendFormat(" ORDER BY {0}", tranResult.OrderString); } break; } #endregion using (var conn = DbServerFactory.GetConnection(server)) { return(await conn.ExecuteScalarAsync <T>(cmdText.ToString(), tranResult.Parameters, commandType : GetCommandType(cmd as RdbCommand)).ConfigureAwait(false)); } }
public override QueryLinguist CreateLinguist(QueryTranslator translator) { return(new SqlCeLinguist(this, translator)); }
public override QueryPolice CreatePolice(QueryTranslator translator) { return new OQueryPolice(this, translator); }
public AdvancedMapper(AdvancedMapping mapping, QueryTranslator translator) : base(mapping, translator) { this.mapping = mapping; }
public BasicMapper(BasicMapping mapping, QueryTranslator translator) { this.mapping = mapping; this.translator = translator; }
private void DoToken(string token, QueryTranslator q) { if (q.IsName(StringHelper.Root(token))) //path expression { DoPathExpression(q.Unalias(token), q); } else if (token.StartsWith(ParserHelper.HqlVariablePrefix)) //named query parameter { q.AddNamedParameter(token.Substring(1)); // this is only a temporary parameter to help with the parsing of hql - // when the type becomes known then this will be converted to its real // parameter type. AppendToken(q, new SqlString(new object[] { new Parameter(StringHelper.SqlParameter) })); } else if (token.Equals(StringHelper.SqlParameter)) { //if the token is a "?" then we have a Parameter so convert it to a SqlCommand.Parameter // instead of appending a "?" to the WhereTokens q.AppendWhereToken(new SqlString(new object[] { new Parameter(StringHelper.SqlParameter) })); } else { IQueryable persister = q.GetPersisterUsingImports(token); if (persister != null) // the name of a class { object discrim = persister.DiscriminatorSQLValue; if (InFragment.Null == discrim || InFragment.NotNull == discrim) { throw new QueryException("subclass test not allowed for null or not null discriminator"); } AppendToken(q, discrim.ToString()); } else { object constant; string fieldName = null; string typeName = null; string importedName = null; int indexOfDot = token.IndexOf(StringHelper.Dot); // don't even bother to do the lookups if the indexOfDot is not // greater than -1. This will save all the string modifications. // This allows us to resolve to the full type before obtaining the value e.g. FooStatus.OFF -> NHibernate.Model.FooStatus.OFF if (indexOfDot > -1) { fieldName = StringHelper.Unqualify(token); typeName = StringHelper.Qualifier(token); importedName = q.factory.GetImportedClassName(typeName); } if (indexOfDot > -1 && (constant = ReflectHelper.GetConstantValue(importedName, fieldName)) != null) { // need to get the NHibernate Type so we can convert the Enum or field from // a class into it's string representation for hql. IType type; try { type = TypeFactory.HeuristicType(constant.GetType().AssemblyQualifiedName); } catch (MappingException me) { throw new QueryException(me); } if (type == null) { throw new QueryException(string.Format("Could not determin the type of: {0}", token)); } try { AppendToken(q, (( ILiteralType )type).ObjectToSQLString(constant)); } catch (Exception e) { throw new QueryException("Could not format constant value to SQL literal: " + token, e); } } else { //anything else string negatedToken = negated ? ( string )negations[token.ToLower(System.Globalization.CultureInfo.InvariantCulture)] : null; if (negatedToken != null && (!betweenSpecialCase || !"or".Equals(negatedToken))) { AppendToken(q, negatedToken); } else { AppendToken(q, token); } } } } }
public SqlCeLinguist(SqlCeLanguage language, QueryTranslator translator) : base(language, translator) { }
public override QueryMapper CreateMapper(QueryTranslator translator) { return new AdvancedMapper(this, translator); }
public QueryLinguist(QueryLanguage language, QueryTranslator translator) { this.language = language; this.translator = translator; }
public void TestInitialize() { QueryTranslator = new QueryTranslator(); }
public OTypeMapper(BasicMapping mapping, QueryTranslator translator) : base(mapping, translator) { _repoType = ((OTypeMapping)mapping).RepositoryType; }
public void End(QueryTranslator q) { }
/// <summary> /// execute command /// </summary> /// <typeparam name="T">data type</typeparam> /// <param name="server">server</param> /// <param name="cmds">command</param> /// <returns>data numbers</returns> public async Task <int> ExecuteAsync(ServerInfo server, params ICommand[] cmds) { #region group execute commands IQueryTranslator translator = QueryTranslator.GetTranslator(server); List <DbExecuteCommand> executeCommands = new List <DbExecuteCommand>(); var batchExecuteConfig = DataManager.GetBatchExecuteConfig(server.ServerType) ?? BatchExecuteConfig.Default; var groupStatementsCount = batchExecuteConfig.GroupStatementsCount; groupStatementsCount = groupStatementsCount < 0 ? 1 : groupStatementsCount; var groupParameterCount = batchExecuteConfig.GroupParametersCount; groupParameterCount = groupParameterCount < 0 ? 1 : groupParameterCount; StringBuilder commandTextBuilder = new StringBuilder(); CmdParameters parameters = null; int statementsCount = 0; bool forceReturnValue = false; foreach (var cmd in cmds) { DbExecuteCommand executeCommand = GetExecuteDbCommand(translator, cmd as RdbCommand); if (executeCommand == null) { continue; } if (executeCommand.PerformAlone) { if (statementsCount > 0) { executeCommands.Add(new DbExecuteCommand() { CommandText = commandTextBuilder.ToString(), CommandType = CommandType.Text, ForceReturnValue = true, Parameters = parameters }); statementsCount = 0; translator.ParameterSequence = 0; commandTextBuilder.Clear(); parameters = null; } executeCommands.Add(executeCommand); continue; } commandTextBuilder.AppendLine(executeCommand.CommandText); parameters = parameters == null ? executeCommand.Parameters : parameters.Union(executeCommand.Parameters); forceReturnValue |= executeCommand.ForceReturnValue; statementsCount++; if (translator.ParameterSequence >= groupParameterCount || statementsCount >= groupStatementsCount) { executeCommands.Add(new DbExecuteCommand() { CommandText = commandTextBuilder.ToString(), CommandType = CommandType.Text, ForceReturnValue = true, Parameters = parameters }); statementsCount = 0; translator.ParameterSequence = 0; commandTextBuilder.Clear(); parameters = null; } } if (statementsCount > 0) { executeCommands.Add(new DbExecuteCommand() { CommandText = commandTextBuilder.ToString(), CommandType = CommandType.Text, ForceReturnValue = true, Parameters = parameters }); } #endregion return(await ExecuteCommandAsync(server, executeCommands, cmds.Length > 1).ConfigureAwait(false)); }
public CompilerResults compileFromFiles(CompilerParameters parameters, File[] files) { var results = new CompilerResults(); this.context = new CompilerContext(parameters, results); this.statementValidator = new StatementValidator(this.context); this.expressionValidator = new ExpressionValidator(this.context); this.statementValidator.ExpressionValidator = this.expressionValidator; this.expressionValidator.StatementValidator = this.statementValidator; this.reachabilityChecker = new ReachabilityChecker(context); this.assignmentChecker = new AssignmentChecker(context); this.bytecodeGenerator = new BytecodeGenerator(context); bool tragicError = false; var buffer = new char[4096]; var sb = new StringBuilder(); var parser = new Parser(); foreach (var file in files) { sb.setLength(0); InputStreamReader reader = null; try { reader = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8")); int read; while ((read = reader.read(buffer)) != -1) { sb.append(buffer, 0, read); } var text = new char[sb.length()]; sb.getChars(0, sizeof(text), text, 0); if (sizeof(text) > 0) { if (text[sizeof(text) - 1] == '\u001a') { text[sizeof(text) - 1] = ' '; } } var preprocessor = new Preprocessor(results.codeErrorManager, text); preprocessor.Filename = file.getAbsolutePath(); preprocessor.Symbols.addAll(parameters.Symbols); var scanner = new PreprocessedTextScanner(results.codeErrorManager, preprocessor.preprocess()); scanner.Filename = file.getAbsolutePath(); var compilationUnit = parser.parseCompilationUnit(scanner); if (compilationUnit != null) { compilationUnit.Symbols = preprocessor.Symbols; context.CompilationUnits.add(compilationUnit); } } catch (CodeErrorException) { } catch (Exception e) { e.printStackTrace(); tragicError = true; break; } finally { if (reader != null) { try { reader.close(); } catch (IOException) { } } } } if (!tragicError) { if (!context.HasErrors) { if (parameters.ProgressTracker != null) { parameters.ProgressTracker.compilationStageFinished(CompilationStage.Parsing); } doCompile(); } } this.context = null; this.statementValidator = null; this.expressionValidator = null; this.reachabilityChecker = null; this.assignmentChecker = null; this.queryTranslator = null; this.documentationBuilder = null; if (parameters.ProgressTracker != null) { parameters.ProgressTracker.compilationFinished(); } return results; }
public void Test_TagSearch_Translate() { var sp = new TagSearchParameters {Query = "fish"}; var opqs = new QueryTranslator(); var result = new Uri(opqs.Translate(sp)); Assert.AreEqual(_baseUrl.Host, result.Host); Assert.IsTrue(result.Query.Contains("q=fish")); Assert.IsTrue(result.Query.Contains("api-key=" + _key)); }
public AttributeMapper(AttributeMapping mapping, QueryTranslator translator) : base(mapping, translator) { this.mapping = mapping; }
public abstract QueryMapper CreateMapper(QueryTranslator translator);
public override QueryMapper CreateMapper(QueryTranslator translator) { return new BasicMapper(this, translator); }
public OQueryLinguist(QueryLanguage language, QueryTranslator translator) : base(language, translator) { }
private void doTest(String test) { var userDir = System.getProperty("user.dir"); var sourcePath = PathHelper.combine(PathHelper.combine(userDir, "tests/resources/QueryTranslatorTest/sources"), test + ".stab.cs"); var fileReader = new InputStreamReader(new FileInputStream((sourcePath)), Charset.forName("UTF-8")); var code = readToEnd(fileReader); var text = code.toCharArray(); translator = new QueryTranslator(text); var parser = new Parser(); var scanner = new SourceCodeScanner(new CodeErrorManager(), text); var compilationUnit = parser.parseCompilationUnit(scanner); var result = translate(text, compilationUnit); var generatedPath = PathHelper.combine(userDir, "tests/resources/QueryTranslatorTest/generated"); var generatedDir = new File(generatedPath); if (!generatedDir.exists()) { generatedDir.mkdir(); } var fileWriter = new FileWriter(PathHelper.combine(generatedPath, test + ".stab.cs")); fileWriter.write(result); fileWriter.close(); var expectedPath = PathHelper.combine(userDir, "tests/resources/QueryTranslatorTest/expected"); var expectedFile = new File(PathHelper.combine(expectedPath, test + ".stab.cs")); Assert.assertTrue("Expected file not found: " + expectedFile, expectedFile.exists()); fileReader = new InputStreamReader(new FileInputStream((expectedFile)), Charset.forName("UTF-8")); var reference = readToEnd(fileReader); var genReader = new BufferedReader(new StringReader(result)); var refReader = new BufferedReader(new StringReader(reference)); for (;;) { var genLine = genReader.readLine(); var refLine = refReader.readLine(); if (genLine == null && refLine == null) { break; } Assert.assertEquals(refLine, genLine); } }
public void Start(QueryTranslator q) { }