Exemplo n.º 1
0
        protected override IPaginable <Foo> GetPaginableWithLikeRestriction(ISession session)
        {
            var query = new DetachedQuery("f where f.Name like :p1");

            query.SetString("p1", "N_%");
            return(new PaginableQuery <Foo>(session, query));
        }
Exemplo n.º 2
0
        IEnumerable <T> Run(IEnumerable <object> ids)
        {
            var hql = "from " + Type.FullName + " _this ";

            if (ids.HasItems())
            {
                hql += " where _this." + Metadata.IdentifierPropertyName + " in (" + string.Join(",", ids) + ")";
            }
            hql += DoOrderby ? GenerateOrderByString() : string.Empty;

            var hasmanys = Fetch.Where(f => Metadata.PropertyNames.Contains(f) && Metadata.GetPropertyType(f) is CollectionType);

            if (hasmanys.HasItems())
            {
                var q = new DetachedQuery("select _this.Id " + hql);
                if (PageSize != 0)
                {
                    q.SetMaxResults(PageSize).SetFirstResult(PageSize * (Page - 1));
                }
                var fetchids = q.List <T, object>();

                if (fetchids.HasItems())
                {
                    foreach (var f in hasmanys)
                    {
                        var fetchhql = "from " + Type.FullName + " _that ";
                        fetchhql += "left join fetch _that." + f;
                        fetchhql += " where _that." + Metadata.IdentifierPropertyName + " in ( " + string.Join(",", fetchids) + " )";
                        new DetachedQuery(fetchhql).Future <T>();
                    }
                }
            }

            return(RunItemsWithBelongsFetch(ids));
        }
Exemplo n.º 3
0
 /// <summary>
 /// Create a new instance of <see cref="QueryRowsCounter"/>.
 /// </summary>
 /// <param name="hqlRowsCount">The HQL.</param>
 /// <remarks>
 /// If the query is invalid an exception is throw only when <see cref="IRowsCounter.GetRowsCount(ISession)"/>
 /// is called.
 /// </remarks>
 /// <exception cref="ArgumentNullException">If <paramref name="hqlRowsCount"/> is null or empty.</exception>
 public QueryRowsCounter(string hqlRowsCount)
 {
     if (string.IsNullOrEmpty(hqlRowsCount))
     {
         throw new ArgumentNullException("hqlRowsCount");
     }
     dq = new DetachedQuery(hqlRowsCount);
 }
        public void RowsCountUsingParameters()
        {
            IDetachedQuery dq =
                new DetachedQuery("select count(*) from Foo f where f.Name like :p1")
                .SetString("p1", "%1_");
            IRowsCounter rc = new QueryRowsCounter(dq);

            SessionFactory.EncloseInTransaction(s => Assert.AreEqual(5, rc.GetRowsCount(s)));
        }
        public void TransformingShouldDelayingParameterCopy()
        {
            var          originalQuery = new DetachedQuery("from Foo f where f.Name like :p1");
            IRowsCounter rc            = QueryRowsCounter.Transforming(originalQuery);

            originalQuery.SetString("p1", "%1_");

            SessionFactory.EncloseInTransaction(s => Assert.AreEqual(5, rc.GetRowsCount(s)));
        }
Exemplo n.º 6
0
 public PaginableRowsCounterQuery(ISession session, DetachedQuery detachedQuery)
 {
     if (detachedQuery == null)
     {
         throw new ArgumentNullException("detachedQuery");
     }
     this.session       = session;
     this.detachedQuery = detachedQuery;
 }
 protected override IDetachedQuery GetDetachedQuery()
 {
     if (origin != null)
     {
         var result = new DetachedQuery("select count(*) " + origin.Hql);
         result.CopyParametersFrom(origin);
         return(result);
     }
     return(detachedQuery);
 }
Exemplo n.º 8
0
        public IDetachedQuery TransformToRowCount()
        {
            Select s = new Select("count(*)");

            s.SetFrom(from.FromWhereClause());
            DetachedQuery result = new DetachedQuery(s.Clause);

            result.CopyParametersFrom(this);
            return(result);
        }
Exemplo n.º 9
0
        protected override IDetachedQuery GetRowCountQuery()
        {
            if (!detachedQuery.Hql.StartsWith("from", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new HibernateException(string.Format("Can't trasform the HQL to it's counter, the query must start with 'from' clause:{0}", detachedQuery.Hql));
            }
            var result = new DetachedQuery("select count(*) " + detachedQuery.Hql);

            result.CopyParametersFrom(detachedQuery);
            return(result);
        }
        public void ShouldNotTransformAUnsafeHQL()
        {
            var dq = new DetachedQuery("select f.Name from Foo f");

            using (ISession s = SessionFactory.OpenSession())
            {
                IPaginable <Foo> fp = new PaginableRowsCounterQuery <Foo>(s, dq);
                Assert.Throws <HibernateException>(() => ((IRowsCounter)fp).GetRowsCount(s),
                                                   "Should not transform a query with a select clause.");
            }
        }
Exemplo n.º 11
0
        public void RowsCountUsingParameters()
        {
            IDetachedQuery dq =
                new DetachedQuery("select count(*) from Foo f where f.Name like :p1").SetString("p1", "%1_");
            IRowsCounter rc = new QueryRowsCounter(dq);

            using (ISession s = OpenSession())
            {
                Assert.AreEqual(5, rc.GetRowsCount(s));
            }
        }
Exemplo n.º 12
0
        public void RowsCountTransforming()
        {
            DetachedQuery dq = new DetachedQuery("from Foo f where f.Name like :p1");

            dq.SetString("p1", "%1_");
            IRowsCounter rc = QueryRowsCounter.Transforming(dq);

            using (ISession s = OpenSession())
            {
                Assert.AreEqual(5, rc.GetRowsCount(s));
            }
        }
        public void Ctor()
        {
            using (ISession s = SessionFactory.OpenSession())
            {
                Assert.Throws <ArgumentNullException>(() => new PaginableRowsCounterQuery <Foo>(s, null),
                                                      "Should not accept null query");
            }
            var dq = new DetachedQuery("from Foo f where f.Name like :p1");

            Assert.Throws <ArgumentNullException>(() => new PaginableRowsCounterQuery <Foo>(null, dq),
                                                  "Should not accept null session");
        }
        public void RowsCountTransforming()
        {
            Assert.Throws <ArgumentNullException>(() => QueryRowsCounter.Transforming(null));

            var originalQuery = new DetachedQuery("from Foo f where f.Name like :p1");

            originalQuery.SetString("p1", "%1_");

            IRowsCounter rc = QueryRowsCounter.Transforming(originalQuery);

            SessionFactory.EncloseInTransaction(s => Assert.AreEqual(5, rc.GetRowsCount(s)));
        }
Exemplo n.º 15
0
        public void PaginableRowsCount()
        {
            DetachedQuery dq = new DetachedQuery("from Foo f where f.Name like :p1");

            dq.SetString("p1", "N_");
            using (ISession s = OpenSession())
            {
                IPaginable <Foo> fp = new PaginableRowsCounterQuery <Foo>(LastOpenedSession, dq);
                IList <Foo>      l  = fp.GetPage(5, 1);
                Assert.AreEqual(5, l.Count);
                Assert.AreEqual(10, ((IRowsCounter)fp).GetRowsCount(s));
            }
        }
        public void ShouldWorkAsPaginatorAndAsRowCounter()
        {
            var dq = new DetachedQuery("from Foo f where f.Name like :p1");

            dq.SetString("p1", "N_");
            using (ISession s = SessionFactory.OpenSession())
            {
                IPaginable <Foo> fp = new PaginableRowsCounterQuery <Foo>(s, dq);
                IList <Foo>      l  = fp.GetPage(5, 1);
                Assert.That(l.Count, Is.EqualTo(5));
                Assert.That(((IRowsCounter)fp).GetRowsCount(s), Is.EqualTo(10));
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Transform an gigen <see cref="DetachedQuery"/> (HQL query) to it's rows count.
        /// </summary>
        /// <param name="query">The given <see cref="DetachedQuery"/>.</param>
        /// <returns>
        /// A <see cref="QueryRowsCounter"/> based on <paramref name="query"/>, with row count, using
        /// same parameters and it's values.
        /// </returns>
        /// <exception cref="HibernateException">When the query don't start with 'from' clause.</exception>
        /// <remarks>
        /// Take care to the query; it can't contain any other clause than "from" and "where".
        /// Set the parameters and it's values, of <paramref name="query"/> befor call this method.
        /// </remarks>
        public static QueryRowsCounter Transforming(DetachedQuery query)
        {
            if (!query.Hql.StartsWith("from", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new HibernateException(
                          string.Format(
                              "Can't trasform the HQL to it's counter, the query must start with 'from' clause:{0}", query.Hql));
            }
            QueryRowsCounter result = new QueryRowsCounter("select count(*) " + query.Hql);

            result.CopyParametersFrom(query);
            return(result);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Create a <see cref="DetachedQuery"/> by hql statement with parameters
        /// </summary>
        /// <param name="hql">실행할 HQL 문</param>
        /// <param name="parameters">파리미터</param>
        /// <returns>쿼리 객체</returns>
        public static IDetachedQuery CreateDetachedQuery(string hql, params INHParameter[] parameters)
        {
            hql.ShouldNotBeWhiteSpace("hql");

            var detachedQuery = new DetachedQuery(hql);

            if (parameters != null && parameters.Length > 0)
            {
                SetDetachedQueryParameters(detachedQuery, parameters);
            }

            return(detachedQuery);
        }
Exemplo n.º 19
0
        public Repository(ISessionFactory sessionFactory, ISession session)
        {
            this.session        = session ?? throw new ArgumentNullException("session", "未能获取 ISession的实例。");
            this.sessionFactory = sessionFactory ?? throw new ArgumentNullException("sessionFactory", "仓储层需要根据 ISessionFactory 获取Session,但未能获取 ISessionFactory 的实例。");

            ClassMetadata          = sessionFactory.GetClassMetadata(persistentClass);
            identifierPropertyName = ClassMetadata.IdentifierPropertyName;
            entityName             = ClassMetadata.EntityName;
            queryAllString         = $"from {entityName}";
            allQuery = new DetachedQuery($"from {entityName}");

            allCountQuery     = new DetachedQuery($"select count(*) from {entityName}");
            inIdentitiesQuery = new DetachedQuery($"from {entityName} where {identifierPropertyName} in (:identities)");
        }
Exemplo n.º 20
0
        public void Serializable()
        {
            DetachedQuery dq = new DetachedQuery("from Foo f where f.Name=:pn and f.Description=:pd");

            dq.SetString("pn", "N2").SetString("pd", "D2");
            byte[] bytes = SerializationHelper.Serialize(dq);

            DetachedQuery dqs = (DetachedQuery)SerializationHelper.Deserialize(bytes);

            using (ISession s = OpenSession())
            {
                dqs.GetExecutableQuery(s).List();
            }
        }
        /// <summary>
        /// Transform an gigen <see cref="DetachedQuery"/> (HQL query) to it's rows count.
        /// </summary>
        /// <param name="origin">The given <see cref="DetachedQuery"/>.</param>
        /// <returns>
        /// A <see cref="QueryRowsCounter"/> based on <paramref name="origin"/>, with row count, using
        /// same parameters and it's values.
        /// </returns>
        /// <exception cref="HibernateException">When the query don't start with 'from' clause.</exception>
        /// <remarks>
        /// Take care to the query; it can't contain any other clause than "from" and "where".
        /// Set the parameters and it's values, of <paramref name="origin"/> befor call this method.
        /// </remarks>
        public static QueryRowsCounter Transforming(DetachedQuery origin)
        {
            if (origin == null)
            {
                throw new ArgumentNullException("origin");
            }
            if (!origin.Hql.StartsWith("from", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new HibernateException(
                          string.Format("Can't trasform the HQL to it's counter, the query must start with 'from' clause:{0}", origin.Hql));
            }
            var result = new QueryRowsCounter(origin);

            return(result);
        }
Exemplo n.º 22
0
        public void WithSelfCounter()
        {
            DetachedQuery dq = new DetachedQuery("from Foo f where f.Name like :p1");

            dq.SetString("p1", "%1_");
            IPaginable <Foo> fp = new PaginableRowsCounterQuery <Foo>(LastOpenedSession, dq);

            Paginator <Foo> ptor = new Paginator <Foo>(2, fp);

            Assert.IsTrue(ptor.AutoCalcPages);
            Assert.AreEqual(3, ptor.LastPageNumber);
            // check page 2
            IList <Foo> lpage = ptor.GetPage(2);

            Assert.AreEqual(2, lpage.Count);
            Assert.AreEqual(2, ptor.CurrentPageNumber);
            Assert.AreEqual("N12", lpage[0].Name);
            Assert.AreEqual("N13", lpage[1].Name);
        }
Exemplo n.º 23
0
        IEnumerable <T> RunItemsWithBelongsFetch(IEnumerable <object> ids)
        {
            var belongs = Fetch.Where(f => Metadata.PropertyNames.Contains(f) && Metadata.GetPropertyType(f) is EntityType);
            var hql     = "from " + Type.FullName + " _this ";

            hql += belongs.Select(f => " left join fetch _this." + f).Join(" ");
            if (ids.HasItems())
            {
                hql += " where _this." + Metadata.IdentifierPropertyName + " in (" + string.Join(",", ids) + ")";
            }
            hql += GenerateOrderByString();
            var q = new DetachedQuery(hql);

            if (PageSize != 0)
            {
                q.SetMaxResults(PageSize).SetFirstResult(PageSize * (Page - 1));
            }
            return(q.Future <T>());
        }
Exemplo n.º 24
0
        public override IEnumerable <T> Run(CompositeNode rootnode, ref IFutureValue <long> count)
        {
            GenerateQuery(rootnode);
            var ids = LuceneSearchHelper.GetIds(Type, BaseQuery).ToList();

            if (ids.IsEmpty() && !string.IsNullOrEmpty(BaseQuery.ToString()))
            {
                ids.Add(0);
            }

            var hql = "from " + Type.FullName + " _this ";

            if (ids.HasItems())
            {
                hql += " where _this." + Metadata.IdentifierPropertyName + " in (" + string.Join(",", ids) + ")";
            }
            count = new DetachedQuery("select count(*) " + hql).FutureValue <T, long>();
            return(Run(ids));
        }
        public void ToRowCount()
        {
            Select s = new Select("f.Name, f.Description, b.Descriptoin").From("Foo f");

            s.From().Join("f.Bar b");
            Where where = new Where();
            where.And("f.Name like :pName");
            where.And("b.Asociated > :pAso");
            s.From().SetWhere(where);
            OrderBy order = new OrderBy().Add("b.Asociated", true);

            order.Add("f.Name");
            s.From().SetOrderBy(order);

            DetachedDynQuery ddq = new DetachedDynQuery(s);
            DetachedQuery    drc = (DetachedQuery)ddq.TransformToRowCount();

            Assert.AreEqual("select count(*) from Foo f join f.Bar b where ((f.Name like :pName) and (b.Asociated > :pAso))",
                            drc.Hql);
        }
Exemplo n.º 26
0
        public void PerformanceDiffSimplyQuery()
        {
            DateTime      sDQStart = DateTime.Now;
            DetachedQuery dq       = new DetachedQuery("from Foo f where f.Name=:pn and f.Description=:pd");

            dq.SetString("pn", "N2").SetString("pd", "D2");
            using (ISession s = OpenSession())
            {
                IQuery q = dq.GetExecutableQuery(s);
            }
            DateTime sDQStop = DateTime.Now;

            DateTime sQStart = DateTime.Now;

            using (ISession s = OpenSession())
            {
                IQuery q = s.CreateQuery("from Foo f where f.Name=:pn and f.Description=:pd").SetString("pn", "N2").SetString("pd", "D2");
            }
            DateTime sQStop = DateTime.Now;

            Console.WriteLine("DetachedQueryCycle={0} QueryCycl={1}  Diff={2}", sDQStop - sDQStart, sQStop - sQStart,
                              (sDQStop - sDQStart) - (sQStop - sQStart));
        }
Exemplo n.º 27
0
        public void ExecutableQuery()
        {
            // Simply fetch
            IDetachedQuery dq = new DetachedQuery("from Foo");

            using (ISession s = OpenSession())
            {
                IQuery q = dq.GetExecutableQuery(s);
                IList  l = q.List();
                Assert.AreEqual(totalFoo, l.Count);
            }

            // With Typed Parameters
            dq = new DetachedQuery("from Foo f where f.Name=:pn and f.Description=:pd");
            dq.SetString("pn", "N2").SetString("pd", "D2");
            using (ISession s = OpenSession())
            {
                IQuery      q = dq.GetExecutableQuery(s);
                IList <Foo> l = q.List <Foo>();
                Assert.AreEqual(1, l.Count);
                Assert.AreEqual("N2", l[0].Name);
                Assert.AreEqual("D2", l[0].Description);
            }

            // With UnTyped Parameters
            dq = new DetachedQuery("from Foo f where f.Name=:pn and f.Description=:pd");
            dq.SetParameter("pn", "N2").SetParameter("pd", "D2");
            using (ISession s = OpenSession())
            {
                IQuery      q = dq.GetExecutableQuery(s);
                IList <Foo> l = q.List <Foo>();
                Assert.AreEqual(1, l.Count);
                Assert.AreEqual("N2", l[0].Name);
                Assert.AreEqual("D2", l[0].Description);
            }

            // With UnTyped Parameter List
            dq = new DetachedQuery("from Foo f where f.IntValue in (:pn)");
            dq.SetParameterList("pn", new int[] { 2, 3 });
            using (ISession s = OpenSession())
            {
                IQuery      q = dq.GetExecutableQuery(s);
                IList <Foo> l = q.List <Foo>();
                Assert.AreEqual(2, l.Count);

                Assert.True(l.Contains(new Foo("N2", "D2")));
                Assert.True(l.Contains(new Foo("N3", "D3")));
            }

            // Pagination
            dq = new DetachedQuery("from Foo f order by f.IntValue");
            dq.SetFirstResult(0).SetMaxResults(2);
            using (ISession s = OpenSession())
            {
                IQuery      q = dq.GetExecutableQuery(s);
                IList <Foo> l = q.List <Foo>();
                Assert.AreEqual(2, l.Count);
                Assert.AreEqual("N0", l[0].Name);
                Assert.AreEqual("N1", l[1].Name);
            }
            dq.SetFirstResult(2).SetMaxResults(1);
            using (ISession s = OpenSession())
            {
                IQuery      q = dq.GetExecutableQuery(s);
                IList <Foo> l = q.List <Foo>();
                Assert.AreEqual(1, l.Count);
                Assert.AreEqual("N2", l[0].Name);
            }
        }
Exemplo n.º 28
0
        public void FullCreamIntegration()
        {
            // Fill DB
            SessionFactory.EncloseInTransaction(session =>
            {
                for (int i = 0; i < 10; i++)
                {
                    session.Save(new MusicCD {
                        Name = "Music" + (i / 2)
                    });
                    session.Save(new Antique {
                        Name = "Antique" + (i / 2)
                    });
                }
            });

            // Queries
            var musicQuery =
                new DetachedQuery("select m.Name, count(*) from MusicCD m group by m.Name")
                .SetCacheable(true)
                .SetCacheRegion("SearchStatistics");

            var antiquesQuery =
                new DetachedQuery("select a.Name, count(*) from Antique a group by a.Name")
                .SetCacheable(true)
                .SetCacheRegion("SearchStatistics");

            // Clear SessionFactory Statistics
            SessionFactory.Statistics.Clear();

            // Put in second-level-cache
            SessionFactory.EncloseInTransaction(session =>
            {
                musicQuery.GetExecutableQuery(session).List();
                antiquesQuery.GetExecutableQuery(session).List();
            });

            // Asserts after execution
            SessionFactory.Statistics.QueryCacheHitCount
            .Should("not hit the query cache").Be.EqualTo(0);

            SessionFactory.Statistics.QueryExecutionCount
            .Should("execute both queries").Be.EqualTo(2);

            // Update both tables
            SessionFactory.EncloseInTransaction(session =>
            {
                session.Save(new MusicCD {
                    Name = "New Music"
                });
                session.Save(new Antique {
                    Name = "New Antique"
                });
            });

            // Clear SessionFactory Statistics again
            SessionFactory.Statistics.Clear();

            // Execute both queries again
            SessionFactory.EncloseInTransaction(session =>
            {
                musicQuery.GetExecutableQuery(session).List();
                antiquesQuery.GetExecutableQuery(session).List();
            });

            // Asserts after execution
            SessionFactory.Statistics.QueryCacheHitCount
            .Should("Hit the query cache").Be.EqualTo(1);

            SessionFactory.Statistics.QueryExecutionCount
            .Should("execute only the query for Antiques").Be.EqualTo(1);

            // Clear SessionFactory Statistics again
            SessionFactory.Statistics.Clear();

            // Wait for cache expiration
            Thread.Sleep(new TimeSpan(0, 0, 10));
            // Execute
            SessionFactory.EncloseInTransaction(session => musicQuery.GetExecutableQuery(session).List());

            SessionFactory.Statistics.QueryCacheHitCount
            .Should("Not hit the query cache because stale").Be.EqualTo(0);

            SessionFactory.Statistics.QueryExecutionCount
            .Should("execute the query for MusicCD").Be.EqualTo(1);

            // Cleanup
            SessionFactory.EncloseInTransaction(session =>
            {
                session.Delete("from MusicCD");
                session.Delete("from Antique");
            });
        }
Exemplo n.º 29
0
 public IList <TType> GetList <TType>(DetachedQuery dq)
 {
     return(dq.GetExecutableQuery(Session).List <TType>());
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="origin"></param>
 /// <returns></returns>
 public IRowsCounter CopyParametersFrom(DetachedQuery origin)
 {
     origin.SetParametersTo(dq);
     return(this);
 }