Exemplo n.º 1
0
 /// <summary>
 /// Parse waebric file which is specified
 /// </summary>
 /// <param name="filename">Path to Waebricfile which should be parsed</param>
 public void Parse(String filename)
 {
     try
     {
         Root = null; //Dereference old tree
         Root = (Node)Parser.Parse(filename, ErrorReporter.Standard);
     }
     catch
     {   //Error so no AST
         Root = null;
     }
 }
Exemplo n.º 2
0
        private void ProcessMatches(ProcessingFileInfo file, IReadOnlyCollection <Match> matches)
        {
            var bests = matches != null?_matchRanker.OrderBest(matches) : null;

            foreach (var best in bests)
            {
                Logger.Info($"Parsing '{file.File}'");
                file.State = ProcessingState.Parsing;

                ParseResult result = null;
                lock (ServiceType.GetTypeByUrl(best.Url))
                {
                    try
                    {
                        var parseTask = _parser.Parse(best.Url);
                        parseTask.Wait(_cancelToken);
                        result = parseTask.Result;
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, $"Error while parsing file '{file.File}'");
                    }
                }

                if (result == null)
                {
                    continue;
                }
                var newFilePath = MoveFile(file, _settings.DownloadedDirPath);
                try
                {
                    JsonHelper.SaveJson(newFilePath, best, result);
                }
                catch (Exception e)
                {
                    FileError(file, e, $"Error while saving data for file '{file.File}'");
                }

                FinishFile(file);
                return;
            }

            Logger.Info($"No match for '{file.File}'");
            file.State = ProcessingState.Saving;
            MoveFile(file, _settings.NoMatchDirPath);
            FinishFile(file);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Returns a new core command that when executed materializes the operation this instance
        /// refers to, or null if that command cannot be generated for any reasons.
        /// </summary>
        /// <returns>A new core command, or null.</returns>
        public IQueryCommand GenerateCoreCommand()
        {
            var cmd = _Template == null ? null : _Template.Clone(); if (cmd != null)

            {
                var name = Map.Table;
                if (_MasterAlias != null)
                {
                    name = string.Format("{0} AS {1}", name, _MasterAlias);
                }
                cmd.From(x => name);

                foreach (var entry in Map.Schema)
                {
                    name = entry.ColumnName;
                    if (_MasterAlias != null)
                    {
                        name = string.Format("{0}.{1}", _MasterAlias, name);
                    }
                    cmd.Select(x => name);
                }

                if (Map.Discriminator != null)
                {
                    if (_MasterAlias == null)
                    {
                        cmd.Where(Map.Discriminator);
                    }
                    else
                    {
                        var parser = DynamicParser.Parse(Map.Discriminator);
                        var result = parser.Result;

                        var host = new DynamicNode.GetMember(
                            new DynamicNode.Argument(parser.DynamicArguments.First().Name),
                            _MasterAlias);

                        MasterVisitor(host, (DynamicNode)result);
                        cmd.Where(x => parser.Result);
                    }
                }
            }
            return(cmd);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Defines the names and values of the columns affected by this command, or adds the new
        /// ones to any previous one that may exist.
        /// </summary>
        /// <param name="columns">A collection of dynamic lambda expressions resolving into the
        /// column and values affected by this command using a 'x => x.Column = Value' syntax,
        /// where the value part can be any valid SQL sentence.</param>
        /// <returns>A self-reference to permit a fluent syntax chaining.</returns>
        public IUpdateCommand Columns(params Func <dynamic, object>[] columns)
        {
            if (IsDisposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }
            if (columns == null)
            {
                throw new ArgumentNullException("columns", "Array of specifications cannot be null.");
            }

            for (int i = 0; i < columns.Length; i++)
            {
                string main  = null;
                string value = null;

                var parser = DynamicParser.Parse(columns[i]);
                var result = parser.Result; if (result == null)
                {
                    throw new ArgumentException(
                              "Expression #{0} '{1}' cannot resolve to null.".FormatWith(i, parser));
                }

                while (true)
                {
                    if (result is string)
                    {
                        var node  = ((string)result).Trim();
                        var parts = node.Split('='); if (parts.Length < 2)
                        {
                            throw new ArgumentException(
                                      "Specification #{0} contains no '=' symabol while parsing '{1}'.".FormatWith(i, parser));
                        }

                        main  = parts[0].Trim();
                        value = parts[1].Trim();
                        break;
                    }

                    if (result is DynamicNode.SetMember)
                    {
                        var node = (DynamicNode.SetMember)result;
                        var host = Link.Engine.Parser.Parse(node.Host);

                        main  = host == null ? node.Name : "{0}.{1}".FormatWith(host, node.Name);
                        value = Link.Engine.Parser.Parse(node.Value, Parameters);
                        break;
                    }

                    if (result is DynamicNode.Binary)
                    {
                        var node = (DynamicNode.Binary)result;
                        if (node.Operation == ExpressionType.Equal)
                        {
                            main  = Link.Engine.Parser.Parse(node.Left);
                            value = Link.Engine.Parser.Parse(node.Right, Parameters);
                            break;
                        }
                    }

                    throw new ArgumentException(
                              "Invalid column specification while parsing #{0} '{1}'.".FormatWith(i, parser));
                }

                main  = main.Validated("Column");
                value = value.Validated("Value");

                var str = "{0} = {1}".FormatWith(main, value);
                TheDataColumns = TheDataColumns == null ? str : "{0}, {1}".FormatWith(TheDataColumns, str);

                parser.Dispose();
            }

            return(this);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Defines the contents of the WHERE clause or append the new ones to any previous
        /// specification.
        /// <para>By default if any previous contents exist the new ones are appended using an AND
        /// operator. However, the virtual extension methods 'x => x.And(...)' and 'x => x.Or(...)'
        /// can be used to specify what logical operator to use.</para>
        /// </summary>
        /// <param name="where">The dynamic lambda expression that resolves into the contents of
        /// this clause.</param>
        /// <returns>A self-reference to permit a fluent syntax chaining.</returns>
        public IUpdateCommand Where(Func <dynamic, object> where)
        {
            if (IsDisposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }
            if (where == null)
            {
                throw new ArgumentNullException("where", "Specification cannot be null.");
            }

            string main = null;
            bool   and  = true;

            var parser = DynamicParser.Parse(where);
            var result = parser.Result; if (result == null)

            {
                throw new ArgumentException(

                          "Expression '{0}' cannot resolve to null.".FormatWith(parser));
            }

            while (true)
            {
                if (result is string)
                {
                    main = ((string)result).Trim();
                    if (main.ToUpper().IndexOf("OR ") == 0)
                    {
                        and = false; main = main.Substring(3);
                    }
                    if (main.ToUpper().IndexOf("AND ") == 0)
                    {
                        and = true; main = main.Substring(4);
                    }
                    break;
                }

                if (result is DynamicNode.Method)
                {
                    var node = (DynamicNode.Method)result;
                    var name = node.Name.ToUpper();

                    if ((name == "AND" || name == "OR") && (node.Host is DynamicNode.Argument))
                    {
                        if (node.Arguments == null)
                        {
                            throw new ArgumentException("Virtual method '{0}()' cannot be parameterless while parsing '{0}'.".FormatWith(name, parser));
                        }
                        if (node.Arguments.Length != 1)
                        {
                            throw new ArgumentException("Virtual method '{0}()' can only have one argument while parsing '{0}'.".FormatWith(name, parser));
                        }
                        if (node.Arguments[0] == null)
                        {
                            throw new ArgumentException("Argument of virtual method '{0}()' cannot be null while parsing '{0}'.".FormatWith(name, parser));
                        }

                        and    = (name == "AND");
                        result = node.Arguments[0];
                    }
                }

                main = Link.Engine.Parser.Parse(result, pc: Parameters);
                break;
            }

            main = main.Validated("Where");

            if (TheWhereData == null)
            {
                TheWhereData = main;
            }
            else
            {
                TheWhereData = "{0} {1} {2}".FormatWith(TheWhereData, and ? "AND" : "OR", main);
            }

            parser.Dispose();

            return(this);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Parses the given object, including any arbitrary command logic expressed as a
        /// dynamic lambda expression, and returns an string that can be understood by the
        /// underlying database engine.
        /// </summary>
        /// <param name="obj">The object to parse. It can be any object or reference, including
        /// null ones and dynamic lambda expressions.</param>
        /// <param name="pc">If not null the collection of parameters where to place the ones
        /// extracted from the object to parse. If null their string representation is used
        /// instead.</param>
        /// <param name="nulls">If true null references are accepted. Otherwise an exception is
        /// thrown.</param>
        /// <returns>A string contained the parsed input in a syntax that can be understood by
        /// the underlying database engine.</returns>
        public string Parse(object obj, IParameterCollection pc = null, bool nulls = true)
        {
            if (IsDisposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }

            DynamicParser parser = null; Func <string> dispatch = () =>

            {
                if (obj != null)
                {
                    if (obj is Delegate)
                    {
                        parser = DynamicParser.Parse((Delegate)obj);
                        obj    = parser.Result;
                    }
                }

                if (obj != null)
                {
                    if (obj is ICoreCommandProvider)
                    {
                        return(OnParseCoreCommandProvider((ICoreCommandProvider)obj, pc, nulls));
                    }
                    if (obj is ICommand)
                    {
                        return(OnParseCommand((ICommand)obj, pc, nulls));
                    }
                    if (obj is DynamicNode.Argument)
                    {
                        return(OnParseArgument((DynamicNode.Argument)obj));
                    }
                    if (obj is DynamicNode.GetMember)
                    {
                        return(OnParseGetMember((DynamicNode.GetMember)obj, pc, nulls));
                    }
                    if (obj is DynamicNode.GetIndexed)
                    {
                        return(OnParseGetIndexedMember((DynamicNode.GetIndexed)obj, pc, nulls));
                    }
                    if (obj is DynamicNode.SetMember)
                    {
                        return(OnParseSetMember((DynamicNode.SetMember)obj, pc, nulls));
                    }
                    if (obj is DynamicNode.SetIndexed)
                    {
                        return(OnParseSetIndexedMember((DynamicNode.SetIndexed)obj, pc, nulls));
                    }
                    if (obj is DynamicNode.Unary)
                    {
                        return(OnParseUnary((DynamicNode.Unary)obj, pc, nulls));
                    }
                    if (obj is DynamicNode.Binary)
                    {
                        return(OnParseBinary((DynamicNode.Binary)obj, pc, nulls));
                    }
                    if (obj is DynamicNode.Method)
                    {
                        return(OnParseMethod((DynamicNode.Method)obj, pc, nulls));
                    }
                    if (obj is DynamicNode.Invoke)
                    {
                        return(OnParseInvoke((DynamicNode.Invoke)obj, pc, nulls));
                    }
                    if (obj is DynamicNode.Convert)
                    {
                        return(OnParseConvert((DynamicNode.Convert)obj, pc, nulls));
                    }
                }

                return(OnParseConstant(obj, pc));
            };

            if (obj == null && !nulls)
            {
                throw new ArgumentNullException("obj", "Null nodes are not accepted.");
            }

            var str = dispatch(); if (parser != null)

            {
                parser.Dispose();
            }

            return(str);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Creates a new record parsing the collection of dynamic lambda expressions provided,
        /// each with the 'x => x.Table.Column = Value' or 'x => x.Column = Value' forms.
        /// <para>The new record carries its own ad-hoc schema and clones of the values given.</para>
        /// </summary>
        /// <param name="caseSensitiveNames">Whether the table and column names of the schema of
        /// the new record are case sensitive or not.</param>
        /// <param name="specs">The collectoin of dynamic lambda expressions that specify the
        /// contents and schema of the new record.</param>
        /// <returns>A new record.</returns>
        public static IRecord Create(bool caseSensitiveNames, params Func <dynamic, object>[] specs)
        {
            if (specs == null)
            {
                throw new ArgumentNullException("specs", "List of specifications cannot be null.");
            }
            if (specs.Length == 0)
            {
                throw new ArgumentException("List of specifications cannot be empty.");
            }

            var builder = new RecordBuilder(caseSensitiveNames);

            for (int i = 0; i < specs.Length; i++)
            {
                var spec = specs[i];
                if (spec == null)
                {
                    throw new ArgumentNullException("Specification #{0} cannot be null.".FormatWith(i));
                }

                var parser = DynamicParser.Parse(spec);
                var result = parser.Result;
                if (result == null)
                {
                    throw new ArgumentNullException("Specification #{0}: '{1}' cannot resolve to null.".FormatWith(i, parser));
                }

                if (result is DynamicNode.SetMember)                 // The assignation syntax...
                {
                    var node = (DynamicNode.SetMember)result;

                    if (node.Host is DynamicNode.Argument)                     // x.Column = value;
                    {
                        builder[node.Name] = node.Value;
                        continue;
                    }
                    if (node.Host is DynamicNode.GetMember)                     // x.Table.Column = value;
                    {
                        var host = (DynamicNode.GetMember)node.Host;
                        builder[host.Name, node.Name] = node.Value;
                        continue;
                    }
                }
                if (result is DynamicNode.Binary)
                {
                    var node = (DynamicNode.Binary)result;
                    if (node.Operation == ExpressionType.Equal)
                    {
                        var host = (DynamicNode.GetMember)node.Left;

                        if (host.Host is DynamicNode.Argument)                         // x.Column == value;
                        {
                            builder[host.Name] = node.Right;
                            continue;
                        }
                        if (host.Host is DynamicNode.GetMember)                         // x.Table.Column == value;
                        {
                            var member = (DynamicNode.GetMember)host.Host;
                            if (member.Host is DynamicNode.Argument)
                            {
                                builder[member.Name, host.Name] = node.Right;
                                continue;
                            }
                        }
                    }
                }
                throw new ArgumentException("Specification #{0}: '{1}' is invalid.".FormatWith(i, parser));
            }

            var record = builder.Create(); builder.Dispose();

            return(record);
        }