Ejemplo n.º 1
0
        private static void SearchTest(Table table, string queryString, bool highlight = true, string[] columns = null)
        {
            int iterations = 100;

            int[] pageSizes = new int[] { 50, 100, 200, 400 };

            SelectResult result = null;

            foreach (int pageSize in pageSizes)
            {
                SelectQuery query = new SelectQuery();
                query.Columns   = columns ?? new string[] { "*" };
                query.TableName = "Bugs";
                query.Where     = SelectQuery.ParseWhere(queryString);
                query.Count     = (ushort)pageSize;
                if (highlight)
                {
                    query.Highlighter = new Highlighter("[", "]");
                }

                Console.WriteLine("\r\n{0}\r\n", query);

                Trace.Write(String.Format("Querying Bugs ({0})...\r\n", pageSize));

                for (int i = 0; i < iterations; ++i)
                {
                    result = table.Query(query);
                }
            }

            Console.WriteLine("Found {0:n0} items in {1}", result.Total, result.Runtime.ToFriendlyString());
            Console.WriteLine();
            //ShowResult(result.Values);
        }
Ejemplo n.º 2
0
        private static void QueryPerformanceTest(Table table, string fullQueryWhere)
        {
            int passes     = 100;
            int iterations = passes * fullQueryWhere.Length;

            SelectQuery query = new SelectQuery();

            query.Columns     = new string[] { "ID", "Title" };
            query.TableName   = "Bugs";
            query.Count       = 25;
            query.Highlighter = new Highlighter("[", "]");

            SelectResult result = null;

            Trace.Write(String.Format("Querying Bugs [{0:n0} iterations]...\r\n", iterations));
            ProgressWriter p = new ProgressWriter(passes);

            {
                for (int pass = 0; pass < passes; ++pass)
                {
                    for (int index = 1; index <= fullQueryWhere.Length; ++index)
                    {
                        query.Where = SelectQuery.ParseWhere(fullQueryWhere.Substring(0, index));
                        result      = table.Query(query);
                    }

                    p.IncrementProgress();
                }
            }

            Trace.Write(String.Format("\r\n{0}\r\n", query));
            Trace.Write(String.Format("Found {0:n0} items in {1}\r\n", result.Total, result.Runtime.ToFriendlyString()));
            Console.WriteLine();
            ShowResult(result.Values);
        }
Ejemplo n.º 3
0
        public void TestNonSupportedInput()
        {
            var echoModel = new EchoModel();

            echoModel.RegisterModel();

            var model      = nameof(EchoModel);
            var input      = Expression.Value("string");
            var prediction = Function.Prediction(model, input);

            //Due to possibility of optimization on new SQLite, SQLite skips these expensive query calls if there is no document before running a query.
            using (var doc = new MutableDocument()) {
                doc.SetInt("number", 1);
                SaveDocument(doc);
            }

            using (var q = QueryBuilder.Select(SelectResult.Expression(prediction))
                           .From(DataSource.Database(Db))) {
                q.Invoking(x => x.Execute()).Should().Throw <CouchbaseSQLiteException>()
                .Where(x => x.BaseError == SQLiteStatus.Error);
            }

            var dict = new Dictionary <string, object> {
                ["key"] = this
            };

            input      = Expression.Dictionary(dict);
            prediction = Function.Prediction(model, input);

            using (var q = QueryBuilder.Select(SelectResult.Expression(prediction))
                           .From(DataSource.Database(Db))) {
                q.Invoking(x => x.Execute()).Should().Throw <ArgumentException>();
            }
        }
Ejemplo n.º 4
0
        private void Form1_MouseClick(object sender, MouseEventArgs e)
        {
            if (layer == null)
            {
                return;
            }
            GISVertex v = view.ToMapVertex(e.Location);

            Console.WriteLine("mapvertex @" + v.x.ToString() + "|" + v.y.ToString()); //此处鼠标点到地图点的转换???
            //创建点选粗选矩形
            GISSelect s = new GISSelect();
            GISExtent MinSelectExtent = s.BuildExtent(v, view);
            Point     bottomleft      = view.ToScreenPoint(MinSelectExtent.bottomleft);
            Point     upleft          = view.ToScreenPoint(new GISVertex(MinSelectExtent.bottomleft.x, MinSelectExtent.upright.y));
            Point     upright         = view.ToScreenPoint(MinSelectExtent.upright);
            Point     bottomright     = view.ToScreenPoint(new GISVertex(MinSelectExtent.upright.x, MinSelectExtent.bottomleft.y));

            Point[]  points   = new Point[] { bottomleft, upleft, upright, bottomright };
            Graphics graphics = this.CreateGraphics();

            graphics.DrawPolygon(new Pen(GISConst.PolygonBoundaryColor, GISConst.PolygonBoundaryWidth), points);

            SelectResult sr = layer.Select(v, view);

            if (sr == SelectResult.OK)
            {
                UpdateMap();
                //toolStripStatusLabel1.Text = layer.Selection.Count.ToString();
                toolStripStatusLabel2.Text = "click @" + v.x.ToString() + "|" + v.y.ToString();
                UpdateAttributeWindow();
                //statusStrip1.Text = layer.Selection.Count.ToString();
            }
        }
Ejemplo n.º 5
0
        public void Partition_AddOrUpdate_IncludeOnlyFromArray()
        {
            Partition p = new Partition(PartitionMask.All);

            AddColumns(p);

            // Get sample items but ask the partition only to add some of them
            DataBlock block = BuildSampleData();

            int[] itemIndexes                           = new int[] { 0, 1, 2, 3, 4 };
            int[] partitionStartIndexes                 = new int[] { 0, 2 };
            DataBlock.ReadOnlyDataBlock roBlock         = block;
            DataBlock.ReadOnlyDataBlock chainProjection = roBlock.ProjectChain(itemIndexes, partitionStartIndexes[1], 3);
            p.AddOrUpdate(chainProjection, new AddOrUpdateOptions());

            // Verify only the right items were added
            SelectQuery q = new SelectQuery();

            q.Columns           = new string[] { "ID" };
            q.Where             = new AllExpression();
            q.OrderByColumn     = "ID";
            q.OrderByDescending = false;
            SelectResult result = p.Query(q);

            Assert.AreEqual(3, (int)result.Total);
            Assert.AreEqual("11943", result.Values[0, 0].ToString());
            Assert.AreEqual("11999", result.Values[1, 0].ToString());
            Assert.AreEqual("12505", result.Values[2, 0].ToString());
        }
Ejemplo n.º 6
0
        public void Execute(int i)
        {
            var retryCount = 0;
            var rng        = rands[i];

exec:
            var current = new IndexedNode(rootIndex[0], tree[rootIndex[0]]);

            var depth = 0;

            while (current.node.children.length > 0)
            {
                depth++;
                if (depth >= pieceQueue.Length)
                {
                    if (retryCount++ > 10)
                    {
                        retryCounts[i] = retryCount;
                        return;
                    }

                    goto exec;
                }

                Select(ref current, ref rng);
            }

            var selectResult = new SelectResult(current, pieceQueue[depth]);

            selected[i]    = selectResult;
            depths[i]      = depth;
            retryCounts[i] = retryCount;
        }
Ejemplo n.º 7
0
        public void ITable_TypesCheck(Func <ITable> factoryMethod)
        {
            // Define columns and add sample data
            ITable table = factoryMethod();

            AddSampleData(table);

            SelectQuery query = new SelectQuery();

            query.Columns           = new string[] { "ID" };
            query.Count             = 10;
            query.OrderByColumn     = "ID";
            query.OrderByDescending = false;
            SelectResult result = null;

            // Select bugs with false IsDuplicate
            query.Where = SelectQuery.ParseWhere("IsDuplicate = false");
            result      = table.Query(query);
            Assert.AreEqual("11512, 12505", result.Values.GetColumn(0).Join(", "));

            // Select bugs with false (not true) IsDuplicate
            query.Where = SelectQuery.ParseWhere("IsDuplicate != true");
            result      = table.Query(query);
            Assert.AreEqual("11512, 12505", result.Values.GetColumn(0).Join(", "));

            // Select bugs with ActiveTime over an hour
            query.Where = SelectQuery.ParseWhere("ActiveTime > 01:00:00");
            result      = table.Query(query);
            Assert.AreEqual("11512, 11643, 11943", result.Values.GetColumn(0).Join(", "));
        }
Ejemplo n.º 8
0
        public void ITable_ComplexAndOr(Func <ITable> factoryMethod)
        {
            // Define columns and add sample data
            ITable table = factoryMethod();

            AddSampleData(table);

            SelectQuery query = new SelectQuery();

            query.Columns = new string[] { "ID", "Priority" };
            query.Count   = 100;

            SelectResult result = null;

            // Verify OR works with more than two clauses
            query.Where = new OrExpression(new TermExpression("Priority", Operator.Equals, 0), new TermExpression("Priority", Operator.Equals, 1), new TermExpression("Priority", Operator.Equals, 3));
            result      = table.Query(query);
            Assert.AreEqual(5, (int)result.Total);

            // Verify AND works with more than two clauses
            query.Where = new AndExpression(new TermExpression("Title", Operator.Matches, "Sample"), new TermExpression("Priority", Operator.Equals, 3), new TermExpression("ID", Operator.LessThan, 12000));
            result      = table.Query(query);
            Assert.AreEqual(2, (int)result.Total);

            // Bug Coverage: Ensure AND stays empty with multiple clauses
            query.Where = new AndExpression(new TermExpression("Priority", Operator.Equals, 3), new TermExpression("Priority", Operator.Equals, 2), new TermExpression("Priority", Operator.Equals, 3));
            result      = table.Query(query);
            Assert.AreEqual(0, (int)result.Total);
        }
Ejemplo n.º 9
0
        private SelectResult HandleStatement(IStatement statement)
        {
            SelectResult selectResult = null;

            switch (statement.Type)
            {
            case StatementType.CreateStatement:
                HandleStatement((CreateStatement)statement);
                break;

            case StatementType.DropStatement:
                HandleStatement((DropStatement)statement);
                break;

            case StatementType.DeleteStatement:
                HandleStatement((DeleteStatement)statement);
                break;

            case StatementType.InsertStatement:
                HandleStatement((InsertStatement)statement);
                break;

            case StatementType.SelectStatement:
                selectResult = HandleSelectStatement((SelectStatement)statement);
                break;

            case StatementType.ShowStatement:
                selectResult = HandleSelectStatement((ShowStatement)statement);
                break;

            case StatementType.ExecFileStatement:
                throw new Exception("Impossible reach");
            }
            return(selectResult);
        }
Ejemplo n.º 10
0
        private void ITable_CustomColumn(Func <ITable> factoryMethod, Action <ITable> addCustomColumnMethod)
        {
            ITable table = factoryMethod();

            AddSampleData(table);
            addCustomColumnMethod(table);

            SelectQuery query = new SelectQuery();

            query.Columns       = new string[] { "ID", "Priority", "Color" };
            query.Count         = ushort.MaxValue;
            query.OrderByColumn = "ID";
            SelectResult result = table.Query(query);

            Assert.AreEqual("None;Green;Red;Green;Green", result.Values.GetColumn(2).Join(";"));

            // Change a priority of each bug + 1
            DataBlock items = new DataBlock(new string[] { "ID", "Priority" }, (int)result.Total);

            for (int row = 0; row < result.Total; ++row)
            {
                items.SetRow(row, new object[] { (int)result.Values[row, 0], (short)result.Values[row, 1] + 1 });
            }
            table.AddOrUpdate(items, new AddOrUpdateOptions());

            SelectQuery newQuery = new SelectQuery();

            newQuery.Columns       = new string[] { "ID", "Priority", "Color" };
            newQuery.Count         = ushort.MaxValue;
            newQuery.OrderByColumn = "ID";
            SelectResult newResult = table.Query(query);

            Assert.AreEqual("Red;None;Blue;None;None", newResult.Values.GetColumn(2).Join(";"));
        }
Ejemplo n.º 11
0
        private SelectResult HandleSelectStatement(ShowStatement statement)
        {
            List <SchemaRecord> tableSchemas = _catalogManager.GetTablesSchemaRecord();
            SelectResult        result       = new SelectResult();

            result.ColumnDeclarations = new List <AttributeDeclaration>()
            {
                new AttributeDeclaration()
                {
                    AttributeName = "Table", Type = AttributeTypes.Char, CharLimit = 80
                }
            };
            result.Rows = new List <List <AtomValue> >();
            foreach (SchemaRecord tableSchema in tableSchemas)
            {
                List <AtomValue> row = new List <AtomValue>();
                AtomValue        col = new AtomValue();
                col.Type        = AttributeTypes.Char;
                col.CharLimit   = 80;
                col.StringValue = tableSchema.Name;
                row.Add(col);
                result.Rows.Add(row);
            }
            return(result);
        }
        public override IEnumerable <T> DoQuery(NoSqlQuery <T> queryFilters)
        {
            CheckOpenedConnection();

            IExpression whereExpression = Expression.Property("collection").EqualTo(Expression.String(CollectionName));

            // Interpret Linq query to expression
            if (queryFilters.Filter != null)
            {
                var wherePreFilterExpression = Linq2CouchbaseLiteExpression.GenerateFromExpression(queryFilters.Filter);
                if (wherePreFilterExpression != null)
                {
                    whereExpression = whereExpression.And(wherePreFilterExpression);
                }
            }

            var queryBuilder = QueryBuilder.Select(SelectResult.Expression(Meta.ID))
                               .From(DataSource.Database(database))
                               .Where(whereExpression)
                               .Limit(queryFilters.Limit > 0 ? Expression.Int(queryFilters.Limit) : Expression.Int(int.MaxValue));

            IList <string> ids = null;

            using (var query = queryBuilder)
            {
                ids = query.Execute().Select(row => row.GetString("id")).ToList();
            }

            var resultSet = ids.Select(e => GetById(e));

            return(resultSet);
        }
        public override long TruncateCollection()
        {
            CheckOpenedConnection();

            int deleted = 0;

            var documents = new List <Document>();

            using (var query = QueryBuilder.Select(SelectResult.Expression(Meta.ID))
                               .From(DataSource.Database(database))
                               .Where(Expression.Property("collection").EqualTo(Expression.String(CollectionName))))
            {
                foreach (var result in query.Execute())
                {
                    documents.Add(database.GetDocument(result.GetString("id")));
                }
            }

            database.InBatch(() =>
            {
                foreach (var entity in documents)
                {
                    database.Purge(entity);
                    deleted++;
                }
            });

            return(deleted);
        }
Ejemplo n.º 14
0
        private static void DoPredictiveQuery()
        {
            using (var db = new Database("mydb"))
            {
                // tag::predictive-query[]
                var input = Expression.Dictionary(new Dictionary <string, object>
                {
                    ["photo"] = Expression.Property("photo")
                });


                //var prediction = PredictiveModel.predict("ImageClassifier", input); // <1>

                using (var q = QueryBuilder.Select(SelectResult.All())
                               .From(DataSource.Database(db))
                               //.Where(prediction.Property("label").EqualTo(Expression.String("car"))
                               //.And(prediction.Property("probability").GreaterThanOrEqualTo(Expression.Double(0.8))))
                       )
                {
                    var result = q.Execute();
                    Console.WriteLine($"Number of rows: {result.Count()}");
                }
                // end::predictive-query[]
            }
        }
Ejemplo n.º 15
0
        private void Button_Select_Click(object sender, RoutedEventArgs e)
        {
            fileSelected = Selection_File.GetSelection().selectionText + fileExtension;

            // If the network is new the dictionary of the network is not found in the config
            // so we generate default path
            string path;

            path = Config.Instance[Config.Keys.Subjects][subject][algorithm][pathKey];


            string absPath = System.IO.Path.GetFullPath(path);

            switch (selectSource)
            {
            case SelectSource.Processed:
                result = EndSelectionForNew(absPath, fileSelected);
                break;
            }

            if (result == SelectResult.Cancel)
            {
                return;
            }
            else
            {
                Close();
            }
        }
Ejemplo n.º 16
0
    private static void testQueryForID()
    {
        // For Documentation
        var dbName  = "travel-sample";
        var this_Db = new Database(dbName);

        Dictionary <string, object>         hotel  = new Dictionary <string, object>();
        List <Dictionary <string, object> > hotels = new List <Dictionary <string, object> >();


        // tag::query-syntax-id[]
        var query = QueryBuilder
                    .Select(SelectResult.Expression(Meta.ID).As("this_ID")) // <.>
                    .From(DataSource.Database(this_Db));

        // end::query-syntax-id[]


        // tag::query-access-id[]
        var results = query.Execute().AllResults();

        foreach (var result in results)
        {
            var thisDocsID = result.GetString("this_ID");     // <.>
            var doc        = this_Db.GetDocument(thisDocsID);
        }
        //end::query-access-id[]
    }
Ejemplo n.º 17
0
        public SelectResult SelectSql(string sql)
        {
            var result = new SelectResult()
            {
                ColumnNames = new List <string>(),
                Results     = new List <string[]>(),
            };

            using (var uow = _db.UnitOfWork)
            {
                var conn = uow._context.Database.GetDbConnection();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    using (var reader = cmd.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                result.ColumnNames.Add(reader.GetName(i));
                            }
                            while (reader.Read())
                            {
                                var obj = new object[reader.FieldCount];
                                reader.GetValues(obj);
                                result.Results.Add(obj.Select(x => x.ToString()).ToArray());
                            }
                        }
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 18
0
    private static void testQuerySyntaxCount()
    {
        // For Documentation
        var dbName  = "travel-sample";
        var this_Db = new Database(dbName);

        Dictionary <string, object>         hotel  = new Dictionary <string, object>();
        List <Dictionary <string, object> > hotels = new List <Dictionary <string, object> >();

        // tag::query-syntax-count-only[]
        var query =
            QueryBuilder
            .Select(SelectResult.Expression(Function.Count(Expression.All())).As("mycount"))     // <.>
            .From(DataSource.Database(this_Db));

        // end::query-syntax-count-only[]


        // tag::query-access-count-only[]
        var results = query.Execute().AllResults();

        foreach (var result in results)
        {
            var numberOfDocs = result.GetInt("mycount");     // <.>
            // end::query-access-count-only[]
        }
    }
Ejemplo n.º 19
0
        private static void SelectJoin()
        {
            Console.WriteLine("Join");
            var db = _Database;

            // # tag::query-join[]
            using (var query = QueryBuilder.Select(
                       SelectResult.Expression(Expression.Property("name").From("airline")),
                       SelectResult.Expression(Expression.Property("callsign").From("airline")),
                       SelectResult.Expression(Expression.Property("destinationairport").From("route")),
                       SelectResult.Expression(Expression.Property("stops").From("route")),
                       SelectResult.Expression(Expression.Property("airline").From("route")))
                               .From(DataSource.Database(db).As("airline"))
                               .Join(Join.InnerJoin(DataSource.Database(db).As("route"))
                                     .On(Meta.ID.From("airline").EqualTo(Expression.Property("airlineid").From("route"))))
                               .Where(Expression.Property("type").From("route").EqualTo(Expression.String("route"))
                                      .And(Expression.Property("type").From("airline").EqualTo(Expression.String("airline")))
                                      .And(Expression.Property("sourceairport").From("route").EqualTo(Expression.String("RIX"))))) {
                foreach (var result in query.Execute())
                {
                    Console.WriteLine($"Name Property :: {result.GetString("name")}");
                }
            }
            // # end::query-join[]
        }
Ejemplo n.º 20
0
        public static void Execute(Executor executor, SelectCommand setCommand)
        {
            var table = executor.DatabaseSelected.TableSelected;

            var newResult = new SelectResult
            {
                DatabaseName = executor.DatabaseSelected.Name,
                TableName    = table.Name,
                Data         = new Dictionary <uint, Property[]>()
            };

            foreach (var data in table)
            {
                var properties = data.Datasets
                                 .Select(d => new Property
                {
                    Name  = d.Key,
                    Type  = (PropertyType)d.Value.Type,
                    Value = d.Value.Value
                })
                                 .ToArray();

                newResult.Data.Add(data.Id, properties);
            }

            executor.Results.Add(newResult);

            executor.ExecuteNextCommand();
        }
        public void TestPredictiveIndexOnValues()
        {
            CreateDocument(1, 2, 3, 4, 5);
            CreateDocument(6, 7, 8, 9, 10);

            var aggregateModel = new AggregateModel();

            aggregateModel.RegisterModel();

            var model      = nameof(AggregateModel);
            var input      = AggregateModel.CreateInput("numbers");
            var prediction = Function.Prediction(model, input);

            var index = IndexBuilder.PredictiveIndex(model, input, "sum");

            Db.CreateIndex("SumIndex", index);

            aggregateModel.AllowCalls = false;

            using (var q = QueryBuilder.Select(SelectResult.Property("numbers"),
                                               SelectResult.Expression(prediction.Property("sum")).As("sum"))
                           .From(DataSource.Database(Db))
                           .Where(prediction.Property("sum").EqualTo(Expression.Int(15)))) {
                var explain = q.Explain();
                explain.Contains("USING INDEX SumIndex").Should().BeTrue();

                var rows = VerifyQuery(q, (n, result) => { result.GetInt(1).Should().Be(15); });
                aggregateModel.Error.Should().BeNull();
                rows.Should().Be(1);
                aggregateModel.NumberOfCalls.Should().Be(2);
            }
        }
Ejemplo n.º 22
0
        public List <Path> GetExternalPaths(Action <List <Path> > pathsUpdated)
        {
            List <Path> paths = new List <Path>();

            try
            {
                _pathsQuery = QueryBuilder
                              .Select(SelectResult.All())
                              .From(DataSource.Database(DatabaseManager.Database))
                              .Where((Expression.Property("type").EqualTo(Expression.String("path"))
                                      .And(Expression.Property("createdBy").NotEqualTo(Expression.String(AppInstance.AppId)))));

                if (pathsUpdated != null)
                {
                    _pathsQueryToken = _pathsQuery.AddChangeListener((object sender, QueryChangedEventArgs e) =>
                    {
                        if (e?.Results != null && e.Error == null)
                        {
                            paths = e.Results.AllResults()?.ToObjects <Path>(databaseName) as List <Path>;

                            if (paths != null)
                            {
                                pathsUpdated.Invoke(paths);
                            }
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"CanvasRepository GetExternalPaths Exception: {ex.Message}");
            }

            return(paths);
        }
        public void TestValueIndexMultipleValues()
        {
            CreateDocument(1, 2, 3, 4, 5);
            CreateDocument(6, 7, 8, 9, 10);

            var aggregateModel = new AggregateModel();

            aggregateModel.RegisterModel();
            var input         = AggregateModel.CreateInput("numbers");
            var sumPrediction = Function.Prediction(aggregateModel.Name, input).Property("sum");
            var avgPrediction = Function.Prediction(aggregateModel.Name, input).Property("avg");

            var sumIndex = IndexBuilder.ValueIndex(ValueIndexItem.Expression(sumPrediction));

            Db.CreateIndex("SumIndex", sumIndex);
            var avgIndex = IndexBuilder.ValueIndex(ValueIndexItem.Expression(avgPrediction));

            Db.CreateIndex("AvgIndex", avgIndex);

            using (var q = QueryBuilder.Select(SelectResult.Expression(sumPrediction).As("s"),
                                               SelectResult.Expression(avgPrediction).As("a"))
                           .From(DataSource.Database(Db))
                           .Where(sumPrediction.LessThanOrEqualTo(Expression.Int(15)).Or(avgPrediction.EqualTo(Expression.Int(8))))) {
                var explain = q.Explain();
                explain.IndexOf("USING INDEX SumIndex").Should().NotBe(-1, "because the sum index should be used");
                explain.IndexOf("USING INDEX AvgIndex").Should().NotBe(-1, "because the average index should be used");

                var numRows = VerifyQuery(q, (n, r) =>
                {
                    r.Should().Match <Result>(x => x.GetLong(0) == 15 || x.GetLong(1) == 8);
                });
                numRows.Should().Be(2);
            }
        }
        public void TestRegisterAndUnregisterModel()
        {
            CreateDocument(1, 2, 3, 4, 5);
            CreateDocument(6, 7, 8, 9, 10);

            var aggregateModel = new AggregateModel();
            var input          = Expression.Dictionary(new Dictionary <string, object>
            {
                ["numbers"] = Expression.Property("numbers")
            });

            using (var q = QueryBuilder.Select(SelectResult.Property("numbers"),
                                               SelectResult.Expression(Function.Prediction(aggregateModel.Name, input)))
                           .From(DataSource.Database(Db))) {
                Action badAction = () => q.Execute();
                badAction.Should().Throw <CouchbaseSQLiteException>().Which.Error.Should().Be((int)SQLiteStatus.Error);

                aggregateModel.RegisterModel();
                var numRows = VerifyQuery(q, (i, result) =>
                {
                    var numbers = result.GetArray(0)?.ToList();
                    numbers.Should().NotBeEmpty("because otherwise the data didn't come through");
                    var pred = result.GetDictionary(1);
                    pred.Should().NotBeNull();
                    pred.GetLong("sum").Should().Be(numbers.Cast <long>().Sum());
                    pred.GetLong("min").Should().Be(numbers.Cast <long>().Min());
                    pred.GetLong("max").Should().Be(numbers.Cast <long>().Max());
                    pred.GetDouble("avg").Should().Be(numbers.Cast <long>().Average());
                });

                numRows.Should().Be(2);
                aggregateModel.UnregisterModel();
                badAction.Should().Throw <CouchbaseSQLiteException>().Which.Error.Should().Be((int)SQLiteStatus.Error);
            }
        }
        public void TestOrderBy()
        {
            CreateDocument(1, 2, 3, 4, 5);
            CreateDocument(6, 7, 8, 9, 10);

            var aggregateModel = new AggregateModel();

            aggregateModel.RegisterModel();

            var model      = nameof(AggregateModel);
            var input      = AggregateModel.CreateInput("numbers");
            var prediction = Function.Prediction(model, input);

            using (var q = QueryBuilder.Select(SelectResult.Expression(prediction.Property("sum")).As("sum"))
                           .From(DataSource.Database(Db))
                           .Where(prediction.Property("sum").GreaterThan(Expression.Int(1)))
                           .OrderBy(Ordering.Expression(prediction.Property("sum")).Descending())) {
                var rows = VerifyQuery(q, (n, result) =>
                {
                    var sum = result.GetInt(0);
                    sum.Should().Be(n == 1 ? 40 : 15);
                });
                rows.Should().Be(2);
            }
        }
        public void TestValueIndex()
        {
            CreateDocument(1, 2, 3, 4, 5);
            CreateDocument(6, 7, 8, 9, 10);

            var aggregateModel = new AggregateModel();

            aggregateModel.RegisterModel();
            var input         = AggregateModel.CreateInput("numbers");
            var sumPrediction = Function.Prediction(aggregateModel.Name, input).Property("sum");

            var index = IndexBuilder.ValueIndex(ValueIndexItem.Expression(sumPrediction));

            Db.CreateIndex("SumIndex", index);

            using (var q = QueryBuilder.Select(SelectResult.Property("numbers"),
                                               SelectResult.Expression(sumPrediction))
                           .From(DataSource.Database(Db))
                           .Where(sumPrediction.EqualTo(Expression.Int(15)))) {
                q.Explain().IndexOf("USING INDEX SumIndex").Should()
                .NotBe(-1, "because the query should make use of the index");
                var numRows = VerifyQuery(q, (n, r) =>
                {
                    var numbers = r.GetArray(0).Cast <long>().ToList();
                    var sum     = r.GetLong(1);
                    sum.Should().Be(numbers.Sum());
                });

                numRows.Should().Be(1);
                aggregateModel.NumberOfCalls.Should().Be(2,
                                                         "because the value should be cached and not call the prediction function again");
            }
        }
        public void TestWhere()
        {
            CreateDocument(1, 2, 3, 4, 5);
            CreateDocument(6, 7, 8, 9, 10);

            var aggregateModel = new AggregateModel();

            aggregateModel.RegisterModel();

            var model      = nameof(AggregateModel);
            var input      = AggregateModel.CreateInput("numbers");
            var prediction = Function.Prediction(model, input);

            using (var q = QueryBuilder.Select(SelectResult.Property("numbers"),
                                               SelectResult.Expression(prediction.Property("sum")).As("sum"),
                                               SelectResult.Expression(prediction.Property("min")).As("min"),
                                               SelectResult.Expression(prediction.Property("max")).As("max"),
                                               SelectResult.Expression(prediction.Property("avg")).As("avg"))
                           .From(DataSource.Database(Db))
                           .Where(prediction.Property("sum").EqualTo(Expression.Int(15)))) {
                var rows = VerifyQuery(q, (n, result) =>
                {
                    var sum = result.GetInt(1);
                    var min = result.GetInt(2);
                    var max = result.GetInt(3);
                    var avg = result.GetDouble(4);

                    sum.Should().Be(15);
                    min.Should().Be(1);
                    max.Should().Be(5);
                    avg.Should().Be(3.0);
                });
                rows.Should().Be(1);
            }
        }
        public void TestNonSupportedInput()
        {
            var echoModel = new EchoModel();

            echoModel.RegisterModel();

            var model      = nameof(EchoModel);
            var input      = Expression.Value("string");
            var prediction = Function.Prediction(model, input);

            using (var q = QueryBuilder.Select(SelectResult.Expression(prediction))
                           .From(DataSource.Database(Db))) {
                q.Invoking(x => x.Execute()).Should().Throw <CouchbaseSQLiteException>()
                .Where(x => x.BaseError == SQLiteStatus.Error);
            }

            var dict = new Dictionary <string, object> {
                ["key"] = this
            };

            input      = Expression.Dictionary(dict);
            prediction = Function.Prediction(model, input);

            using (var q = QueryBuilder.Select(SelectResult.Expression(prediction))
                           .From(DataSource.Database(Db))) {
                q.Invoking(x => x.Execute()).Should().Throw <ArgumentException>();
            }
        }
        public void TestQueryWithBlobParameter()
        {
            SaveDocument(new MutableDocument());

            var textModel = new TextModel();

            textModel.RegisterModel();

            var input = Expression.Dictionary(new Dictionary <string, object>
            {
                ["text"] = Expression.Parameter("text")
            });
            var prediction = Function.Prediction(textModel.Name, input).Property("wc");

            using (var q = QueryBuilder.Select(SelectResult.Expression(prediction).As("wc"))
                           .From(DataSource.Database(Db))) {
                var parameters = new Parameters();
                parameters.SetBlob("text",
                                   new Blob("text/plain",
                                            Encoding.UTF8.GetBytes("Knox on fox in socks in box.  Socks on Knox and Knox in box.")));
                q.Parameters = parameters;
                var numRows = VerifyQuery(q, (n, r) =>
                {
                    r.GetLong(0).Should().Be(14, "because that is the word count of the sentence in the parameter");
                });
                numRows.Should().Be(1);
                textModel.ContentType.Should().Be("text/plain");
                textModel.UnregisterModel();
            }
        }
        public void TestQueryValueFromDictionaryResult()
        {
            CreateDocument(1, 2, 3, 4, 5);
            CreateDocument(6, 7, 8, 9, 10);

            var aggregateModel = new AggregateModel();

            aggregateModel.RegisterModel();
            var input = Expression.Dictionary(new Dictionary <string, object>
            {
                ["numbers"] = Expression.Property("numbers")
            });

            using (var q = QueryBuilder.Select(SelectResult.Property("numbers"),
                                               SelectResult.Expression(Function.Prediction(aggregateModel.Name, input).Property("sum")).As("sum"))
                           .From(DataSource.Database(Db))) {
                var numRows = VerifyQuery(q, (i, result) =>
                {
                    var numbers = result.GetArray(0)?.ToList();
                    numbers.Should().NotBeEmpty("because otherwise the data didn't come through");
                    var sum = result.GetLong(1);
                    sum.Should().Be(result.GetLong("sum"));
                    sum.Should().Be(numbers.Cast <long>().Sum());
                });

                numRows.Should().Be(2);
                aggregateModel.UnregisterModel();
            }
        }
 public override SelectResult ExecuteSelect(AdamDataSourceSelectingEventArgs arguments)
 {
     var selectResult = new SelectResult<FieldInheritanceDefinition>();
     var definitionCollection = new FieldDefinitionCollection(App);
     var isLastPage = LoadFieldsPage(definitionCollection, arguments);
     var inheritanceDefinitions = LoadDefinitionsFor(definitionCollection).ToList();
     selectResult.SetItems(arguments, inheritanceDefinitions, isLastPage);
     return selectResult;
 }
Ejemplo n.º 32
0
 /// <summary>
 /// Subtitle Search Result Parsing function.
 /// Extracts search results (i.e. Show names) and gets links to them.
 /// If more than one show is found, user gets to select one, otherwise he will be directly forwarded
 /// For now only pages where search links directly to subtitles work
 /// </summary>
 /// <param name="source">HTML Source of the search results page</param>
 /// <param name="SourceURL">URL of the source</param>
 private static void ParseSubtitleSearch(ref string source, string SourceURL)
 {
     if (source == "")
         return;
     SubtitleProvider subprovider = SubtitleProvider.GetCurrentProvider();
     string pattern = subprovider.SearchRegExp;
     RegexOptions ro = RegexOptions.IgnoreCase | RegexOptions.Singleline;
     if (subprovider.SearchRightToLeft)
         ro |= RegexOptions.RightToLeft;
     MatchCollection mc = Regex.Matches(source, pattern, ro);
     if (mc.Count == 0) {
         log.Info("No results found");
     } else if (mc.Count == 1) {
         string url = subprovider.SubtitlesPage;
         url = url.Replace("%L", mc[0].Groups["link"].Value);
         if (subprovider.ConstructLink != "") {
             ConstructLinks(mc[0].Groups["link"].Value);
         } else {
             //GetSubtitleFromSeriesPage(url);
         }
     } else {
         log.Info("Search engine found multiple results at " + SourceURL.Replace(" ", "%20"));
         SelectResult sr = new SelectResult(mc, subprovider, true);
         if (sr.ShowDialog() == DialogResult.Cancel)
             return;
         if (sr.urls.Count == 0)
             return;
         foreach (string str in sr.urls) {
             string url = subprovider.SubtitlesPage;
             url = url.Replace("%L", str);
             if (subprovider.ConstructLink != "") {
                 ConstructLinks(str);
             } else {
                 //GetSubtitleFromSeriesPage(url);
             }
         }
     }
 }