public virtual void AddAfter(IQueryPart part, OperationType operation)
        {
            var first = Parts.LastOrDefault(p => p.OperationType == operation);
            var index = Parts.IndexOf(first) + 1;

            Parts.Insert(index, part);
        }
Ejemplo n.º 2
0
 protected void AppendComma(IQueryPart part, TextWriter writer, IQueryPart parent)
 {
     if (parent != null && parent.Parts.Last() != part)
     {
         writer.Write(", ");
     }
 }
Ejemplo n.º 3
0
        /// <inheritdoc />
        public IQueryBuilder Add(IQueryPart queryPart)
        {
            var target = new QueryBuilderX(this);

            target.ContainerObject.Add(queryPart);
            return(target);
        }
Ejemplo n.º 4
0
        public static string GetQuery(this IQueryPart part)
        {
            StringBuilder sb = new StringBuilder();

            part.BuildQuery(sb);
            return(sb.ToString());
        }
Ejemplo n.º 5
0
        public virtual void Add(IQueryPart part)
        {
            if (IsSealed)
            {
                return;
            }

            _parts.Value.Add(part);
        }
        public virtual void Add(IQueryPart part)
        {
            Parts.Add(part);

            if (AggregatePart == null)
            {
                AggregatePart = part;
            }
        }
Ejemplo n.º 7
0
        private static IQueryPart ComposePart(IQueryPart?existingPart, IQueryPart newPart)
        {
            if (existingPart == null)
            {
                return(newPart);
            }

            return(CombineParts(existingPart, newPart, QueryTokenType.AndOperator, 0));
        }
        public void AddToLast(IQueryPart part, OperationType operation)
        {
            var last = Parts.LastOrDefault(p => p.OperationType == operation);
            if (last == null)
            {
                return;
            }

            last.Add(part);
        }
        public virtual void AddBefore(IQueryPart part, OperationType operation)
        {
            var first = Parts.FirstOrDefault(p => p.OperationType == operation);
            var index = Parts.IndexOf(first);
            if (index < 0)
            {
                index = 0;
            }

            Parts.Insert(index, part);
        }
Ejemplo n.º 10
0
 private static IBinaryQueryOperator CreateOperator(QueryTokenType tokenType, IQueryPart leftPart, IQueryPart rightPart, int tolerance)
 {
     return(tokenType switch
     {
         QueryTokenType.AndOperator => new AndQueryOperator(leftPart, rightPart),
         QueryTokenType.OrOperator => new OrQueryOperator(leftPart, rightPart),
         QueryTokenType.NearOperator => new NearQueryOperator(leftPart, rightPart, tolerance),
         QueryTokenType.PrecedingNearOperator => new PrecedingNearQueryOperator(leftPart, rightPart, tolerance),
         QueryTokenType.PrecedingOperator => new PrecedingQueryOperator(leftPart, rightPart),
         _ => throw new QueryParserException(ExceptionMessages.UnexpectedOperatorInternal, tokenType),
     });
Ejemplo n.º 11
0
        protected void CompileChildParts(IQueryPart part, TextWriter writer, IQueryPartsContainer container)
        {
            if (_compiledParts.AsParallel().Contains(part))
            {
                return;
            }

            _compiledParts.Add(part);

            foreach (var p in part.Parts)
            {
                CompilePart(p, writer, container, part);
            }
        }
Ejemplo n.º 12
0
        private void CompileColumn(IQueryPart part, TextWriter writer)
        {
            var collection = part as IValueCollectionQueryPart;
            if (collection == null)
            {
                writer.Write(part.Compile());
                return;
            }

            var column = collection.GetValue(KeyValuePart.MemberName);
            var type = collection.GetValue(KeyValuePart.MemberType);
            var nullable = collection.GetValue(KeyValuePart.Nullable);

            writer.Write("{0} {1}{2}", column, type, string.IsNullOrEmpty(nullable) || nullable.ToLower() == "true" ? "" : " NOT NULL");
        }
Ejemplo n.º 13
0
        private void CompileForeignKey(IQueryPart part, TextWriter writer)
        {
            var collection = part as IValueCollectionQueryPart;
            if (collection == null)
            {
                writer.Write(part.Compile());
                return;
            }

            var column = collection.GetValue(KeyValuePart.MemberName);
            var reference = collection.GetValue(KeyValuePart.ReferenceTable);
            var referenceMember = collection.GetValue(KeyValuePart.ReferenceMember);
            //var nullable = collection.GetValue(KeyValuePart.Nullable);

            writer.Write("FOREIGN KEY({0}) REFERENCES {1}({2})", column, reference, referenceMember);
        }
Ejemplo n.º 14
0
        public IQuery Parse(IIndexedFieldLookup fieldLookup, string queryText, ITokenizer wordTokenizer)
        {
            if (fieldLookup is null)
            {
                throw new ArgumentNullException(nameof(fieldLookup));
            }

            IQueryPart rootPart = null;

            var state = new QueryParserState(queryText);

            while (state.TryGetNextToken(out var token))
            {
                rootPart = CreateQueryPart(fieldLookup, state, token, wordTokenizer, rootPart);
            }

            return(new Query(rootPart));
        }
Ejemplo n.º 15
0
        private static IQueryPart CreateWordPart(QueryToken queryToken, ITokenizer wordTokenizer)
        {
            var wordParts = CreateWordParts(queryToken, wordTokenizer).ToList();

            if (wordParts.Count == 0)
            {
                throw new QueryParserException(ExceptionMessages.ExpectedAtLeastOneWordPartParsed);
            }

            IQueryPart part = wordParts[0];

            for (var i = 1; i < wordParts.Count; i++)
            {
                part = ComposePart(part, wordParts[i]);
            }

            return(part);
        }
Ejemplo n.º 16
0
        private static IQueryPart CreateQueryPart(
            IIndexedFieldLookup fieldLookup,
            QueryParserState state,
            QueryToken token,
            ITokenizer wordTokenizer,
            IQueryPart rootPart)
        {
            switch (token.TokenType)
            {
            case QueryTokenType.Text:
                return(ComposePart(rootPart, CreateWordPart(token, wordTokenizer)));

            case QueryTokenType.FieldFilter:
                var filteredPart = CreateQueryPart(fieldLookup, state, state.GetNextToken(), wordTokenizer, null);
                if (fieldLookup.TryGetIdForField(token.TokenText, out var fieldId))
                {
                    return(ComposePart(
                               rootPart,
                               new FieldFilterQueryOperator(token.TokenText, fieldId, filteredPart)));
                }

                throw new QueryParserException(ExceptionMessages.UnknownFieldReference, token.TokenText);

            case QueryTokenType.OrOperator:
            case QueryTokenType.AndOperator:
            case QueryTokenType.NearOperator:
            case QueryTokenType.PrecedingNearOperator:
            case QueryTokenType.PrecedingOperator:
                var rightPart = CreateQueryPart(fieldLookup, state, state.GetNextToken(), wordTokenizer, null);
                return(CombineParts(rootPart, rightPart, token.TokenType, token.Tolerance));

            case QueryTokenType.OpenBracket:
                var bracketedPart = state.GetTokensUntil(QueryTokenType.CloseBracket)
                                    .Aggregate((IQueryPart)null, (current, next) => CreateQueryPart(fieldLookup, state, next, wordTokenizer, current));

                return(bracketedPart == null
                               ? rootPart
                               : ComposePart(rootPart, new BracketedQueryPart(bracketedPart)));

            default:
                throw new QueryParserException(ExceptionMessages.UnexpectedTokenEncountered, token.TokenType);
            }
        }
Ejemplo n.º 17
0
        private static IBinaryQueryOperator CombineParts(IQueryPart?existingPart, IQueryPart newPart, QueryTokenType operatorType, int tolerance)
        {
            if (existingPart == null)
            {
                throw new QueryParserException(ExceptionMessages.UnexpectedOperator, operatorType);
            }

            if (existingPart is IBinaryQueryOperator existingBinaryOperator)
            {
                if (existingBinaryOperator.Precedence >= TokenPrecedence(operatorType))
                {
                    existingBinaryOperator.Right = CreateOperator(operatorType, existingBinaryOperator.Right, newPart, tolerance);
                    return(existingBinaryOperator);
                }

                return(CreateOperator(operatorType, existingBinaryOperator, newPart, tolerance));
            }

            return(CreateOperator(operatorType, existingPart, newPart, tolerance));
        }
Ejemplo n.º 18
0
        private static IBinaryQueryOperator CreateOperator(QueryTokenType tokenType, IQueryPart leftPart, IQueryPart rightPart, int tolerance)
        {
            switch (tokenType)
            {
            case QueryTokenType.AndOperator:
                return(new AndQueryOperator(leftPart, rightPart));

            case QueryTokenType.OrOperator:
                return(new OrQueryOperator(leftPart, rightPart));

            case QueryTokenType.NearOperator:
                return(new NearQueryOperator(leftPart, rightPart, tolerance));

            case QueryTokenType.PrecedingNearOperator:
                return(new PrecedingNearQueryOperator(leftPart, rightPart, tolerance));

            case QueryTokenType.PrecedingOperator:
                return(new PrecedingQueryOperator(leftPart, rightPart));

            default:
                throw new QueryParserException(ExceptionMessages.UnexpectedOperatorInternal, tokenType);
            }
        }
        public override void Add(IQueryPart part)
        {
            switch (part.OperationType)
            {
                case OperationType.Include:
                    var field = part as FieldQueryPart;
                    if (field != null)
                    {
                        // add the field to the last QueryPart of type SelectionMap (select a,b,c...)
                        AddToLast(field, OperationType.Select);
                    }

                    if (AggregatePart == null)
                    {
                        AggregatePart = part;
                    }

                    break;

                default:
                    base.Add(part);
                    break;
            }
        }
Ejemplo n.º 20
0
        private void CompileOutputParameterSelect(IQueryPart part, TextWriter writer, IQueryPart parent)
        {
            if (parent != null && parent.Parts.FirstOrDefault(p => p.OperationType == OperationType.OutParameterSelect) == part)
            {
                WriteBlank(writer);
            }

            writer.Write("@{0} AS {0}", part.Compile());

            if (parent != null && parent.Parts.Last() != part)
            {
                writer.Write(", ");
            }
        }
Ejemplo n.º 21
0
 public BracketedQueryPart(IQueryPart statement)
 {
     this.Statement = statement;
 }
Ejemplo n.º 22
0
        private void CompileCreateDatabase(IQueryPart part, TextWriter writer)
        {
            var database = part.Compile();

            writer.WriteLine("DECLARE @device_directory NVARCHAR(520)");
            writer.WriteLine("SELECT @device_directory = SUBSTRING(filename, 1, CHARINDEX(N'master.mdf', LOWER(filename)) - 1)");
            writer.WriteLine("FROM master.dbo.sysaltfiles WHERE dbid = 1 AND fileid = 1");
            //sb.AppendLine(string.Format("EXECUTE (N'CREATE DATABASE {0} ON PRIMARY (NAME = N''Northwind'', FILENAME = N''' + @device_directory + N'{0}.mdf'') LOG ON (NAME = N''Northwind_log'',  FILENAME = N''' + @device_directory + N'{0}.ldf'')')", database));

            writer.WriteLine("EXECUTE (N'CREATE DATABASE {0}", database);
            writer.WriteLine("ON PRIMARY (NAME = N''{0}'', FILENAME = N''' + @device_directory + N'{0}.mdf'')", database);
            writer.WriteLine("LOG ON (NAME = N''{0}_log'',  FILENAME = N''' + @device_directory + N'{0}_log.ldf'')')", database);
            //writer.WriteLine("EXECUTE (N'CREATE DATABASE {0} ON PRIMARY (NAME = N''{0}'', FILENAME = N''' + @device_directory + N'{0}.mdf'') LOG ON (NAME = N''{0}_log'',  FILENAME = N''' + @device_directory + N'{0}.ldf'')')", database);

            //var path = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Data");

            //writer.WriteLine(string.Format("EXECUTE (N'CREATE DATABASE {0}", database));
            //writer.WriteLine(string.Format("ON PRIMARY (NAME = N''{0}'', FILENAME = ''{1}'')", database, Path.Combine(path, database + ".mdf")));
            //writer.WriteLine(string.Format("LOG ON (NAME = N''{0}_log'',  FILENAME = ''{1}'')')", database, Path.Combine(path, database + "_log.ldf")));
        }
Ejemplo n.º 23
0
 private void CompileCommand(string command, IQueryPart part, TextWriter writer)
 {
     writer.Write("{0} {1}", command, part.Compile());
 }
Ejemplo n.º 24
0
        private void CompilePrimaryColumn(IQueryPart part, TextWriter writer)
        {
            var collection = part as IValueCollectionQueryPart;
            if (collection == null)
            {
                writer.Write(part.Compile());
                return;
            }

            var column = collection.GetValue(KeyValuePart.MemberName);
            var type = collection.GetValue(KeyValuePart.MemberType);
            var nullable = collection.GetValue(KeyValuePart.Nullable);
            var autoIncremtent = collection.GetValue(KeyValuePart.AutoIncrement);

            writer.Write("{0} {1} PRIMARY KEY{2}{3}",
                    column,
                    type,
                    string.IsNullOrEmpty(nullable) || nullable.ToLower() == "true" ? "" : " NOT NULL",
                    !string.IsNullOrEmpty(autoIncremtent) && autoIncremtent.ToLower() == "true" ? " AUTOINCREMENT" : "");
        }
 /// <inheritdoc />
 public void Add(IQueryPart queryPart)
 {
     _parts.Add(queryPart);
 }
Ejemplo n.º 26
0
 private void CreateTable(IQueryPart part, TextWriter writer)
 {
     writer.Write("CREATE TABLE IF NOT EXISTS {0} (", part.Compile());
 }
Ejemplo n.º 27
0
        private void CompileJoin(IQueryPart part, TextWriter writer)
        {
            var entityMap = part as IEntityPart;
            if (entityMap == null)
            {
                writer.Write("JOIN {0}", part.Compile());
                return;
            }

            writer.Write("JOIN {0}{1}", entityMap.Entity, string.IsNullOrEmpty(entityMap.EntityAlias) ? string.Empty : string.Format(" {0}", entityMap.EntityAlias));
        }
Ejemplo n.º 28
0
        private void CompileFieldFunction(string function, IQueryPart part, TextWriter writer, IQueryPart parent)
        {
            var field = part as IFieldPart;
            if (field == null)
            {
                // try to compile the expression
                writer.Write(part.Compile());
                return;
            }

            //TODO: EntityAlias is allways null, It has to be able to be set when creating a Count expression
            writer.Write("{0}({1}) AS {2}", function, field.Field, field.FieldAlias ?? field.Field);

            if (parent.Parts.Last() != part)
            {
                writer.Write(",");
            }
        }
Ejemplo n.º 29
0
 protected void CompileFormat(string format, IQueryPart part, TextWriter writer)
 {
     writer.Write(format, part.Compile());
 }
Ejemplo n.º 30
0
        private void CompileMemberEqualsValuePart(IQueryPart part, TextWriter writer, IQueryPart parent)
        {
            var collection = part as IValueCollectionQueryPart;
            if (collection == null)
            {
                writer.Write(part.Compile());
                return;
            }

            var key = collection.GetValue(KeyValuePart.MemberName);
            var value = collection.GetValue(KeyValuePart.Value);

            writer.Write("{0} = {1}", key, value);
            AppendComma(part, writer, parent);
        }
Ejemplo n.º 31
0
 public FieldFilterQueryOperator(string fieldName, byte fieldId, IQueryPart statement)
 {
     this.FieldName = fieldName;
     this.FieldId   = fieldId;
     this.Statement = statement;
 }
Ejemplo n.º 32
0
        protected virtual void CompilePart(IQueryPart part, TextWriter writer, IQueryPartsContainer container, IQueryPart parent = null)
        {
            var compiler = _compilers[part.OperationType];
            compiler(part, writer, container, parent);

            CompileChildParts(part, writer, container);
        }
        public void AddToLast(IQueryPart part, Func<IQueryPart, bool> predicate)
        {
            var last = Parts.LastOrDefault(predicate);
            if (last == null)
            {
                return;
            }

            last.Add(part);
        }
Ejemplo n.º 34
0
        private void CompileParameter(IQueryPart part, TextWriter writer, IQueryPart parent)
        {
            writer.Write(part.Compile());

            if (parent != null && parent.Parts.Last() != part)
            {
                writer.Write(", ");
            }
        }
Ejemplo n.º 35
0
 public PrecedingQueryOperator(IQueryPart left, IQueryPart right)
     : base(left, right)
 {
 }
Ejemplo n.º 36
0
 protected BinaryQueryOperator(IQueryPart left, IQueryPart right)
 {
     this.Left  = left;
     this.Right = right;
 }
Ejemplo n.º 37
0
 public NearQueryOperator(IQueryPart left, IQueryPart right, int tolerance = 5)
     : base(left, right)
 {
     this.Tolerance = tolerance;
 }
Ejemplo n.º 38
0
 private static void VerifyResult(IQuery result, IQueryPart expectedQuery)
 {
     result.Root.ToString().Should().Be(expectedQuery.ToString());
 }
Ejemplo n.º 39
0
 /// <summary>
 /// Constructs a new <see cref="Query"/> object capable of searching against an index.
 /// </summary>
 /// <param name="root">
 /// The root part of the query. Passing this parameter as null is allowed, and causes the query
 /// to always return an empty set of results.
 /// </param>
 public Query(IQueryPart root)
 {
     this.Root = root;
 }
Ejemplo n.º 40
0
        private void RenameTable(IQueryPart part, TextWriter writer)
        {
            var collection = part as IValueCollectionQueryPart;
            if (collection == null)
            {
                writer.Write(part.Compile());
                return;
            }

            var original = collection.GetValue(KeyValuePart.Key);
            var value = collection.GetValue(KeyValuePart.Value);

            writer.Write("ALTER TABLE {0} RENAME TO {1}", original, value);
        }
Ejemplo n.º 41
0
        private void CompileField(IQueryPart part, TextWriter writer, IQueryPart parent)
        {
            var field = part as IFieldPart;
            if (field == null)
            {
                // try to compile the expression
                writer.Write(part.Compile());
                return;
            }

            if (!string.IsNullOrEmpty(field.EntityAlias) || !string.IsNullOrEmpty(field.Entity))
            {
                writer.Write(" {0}.", field.EntityAlias ?? field.Entity);
            }
            else
            {
                writer.Write(" ");
            }

            writer.Write(field.Field);

            if (!string.IsNullOrEmpty(field.FieldAlias))
            {
                writer.Write(" AS {0}", field.FieldAlias);
            }

            if (parent != null && parent.Parts.Last() != part)
            {
                writer.Write(",");
            }
        }
Ejemplo n.º 42
0
 protected void CompileValue(IQueryPart part, TextWriter writer)
 {
     writer.Write(part.Compile());
 }
Ejemplo n.º 43
0
 public void Remove(IQueryPart part)
 {
     if (_parts.Value.Contains(part))
     {
         _parts.Value.Remove(part);
     }
 }
Ejemplo n.º 44
0
 public AndQueryOperator(IQueryPart left, IQueryPart right)
     : base(left, right)
 {
 }
 public void Remove(IQueryPart part)
 {
     if (Parts.Contains(part))
     {
         Parts.Remove(part);
     }
 }