Example #1
0
        public void TestSelect()
        {
            using (var session = OpenSqLiteSession())
            {
                var selectedProductDefinition = new ProductDefinition()
                {
                    Id = 1000, MaterialDefinition = new MaterialDefinition {
                        Id = 1
                    }
                };
                session.Save(selectedProductDefinition.MaterialDefinition);
                session.Save(selectedProductDefinition);

                var selectedProducts = new[] { selectedProductDefinition };

                var query = session.Query <Material>()
                            .Where(x => selectedProducts.Contains(x.ProductDefinition) && selectedProducts.Select(y => y.MaterialDefinition).Contains(x.MaterialDefinition));

                var sessionImpl        = session.GetSessionImplementation();
                var factoryImplementor = sessionImpl.Factory;

                var nhLinqExpression  = new NhLinqExpression(query.Expression, factoryImplementor);
                var translatorFactory = new ASTQueryTranslatorFactory();
                var translator        = translatorFactory.CreateQueryTranslators(nhLinqExpression, null, false, sessionImpl.EnabledFilters, factoryImplementor).First();

                TestContext.WriteLine(translator.SQLString);

                Assert.IsNotEmpty(nhLinqExpression.ParameterValuesByName.Values.Where(x => (x.Item1 as IList <ProductDefinition>)?.Contains(selectedProductDefinition) == true));
                Assert.IsNotEmpty(nhLinqExpression.ParameterValuesByName.Values.Where(x => (x.Item1 as IList <MaterialDefinition>)?.Contains(selectedProductDefinition.MaterialDefinition) == true));

                //var result = query.ToList();
            }
        }
        public String GetGeneratedSql(IQueryable queryable, ISession session)
        {
            var sessionImp        = (ISessionImplementor)session;
            var nhLinqExpression  = new NhLinqExpression(queryable.Expression, sessionImp.Factory);
            var translatorFactory = new ASTQueryTranslatorFactory();
            var translators       = translatorFactory.CreateQueryTranslators(nhLinqExpression, null, false, sessionImp.EnabledFilters, sessionImp.Factory);

            return(translators[0].SQLString);
        }
Example #3
0
        public static string ToSqlString(this System.Linq.IQueryable queryable)
        {
            ISession session           = NHibernateSessionManager.Instance.GetSession();
            var      sessionImp        = (ISessionImplementor)session;
            var      nhLinqExpression  = new NhLinqExpression(queryable.Expression, sessionImp.Factory);
            var      translatorFactory = new ASTQueryTranslatorFactory();
            var      translators       = translatorFactory.CreateQueryTranslators(nhLinqExpression, null, false, sessionImp.EnabledFilters, sessionImp.Factory);

            return(translators[0].SQLString);
        }
Example #4
0
        public static string GetGeneratedSql(IQueryable query, ISession session)
        {
            var sessionImpl       = session.GetSessionImplementation();
            var factory           = sessionImpl.Factory;
            var nhLinqExpression  = new NhLinqExpression(query.Expression, factory);
            var translatorFactory = new ASTQueryTranslatorFactory();
            var translator        = translatorFactory.CreateQueryTranslators(nhLinqExpression, null, false, sessionImpl.EnabledFilters, factory).FirstOrDefault();

            return(translator.SQLString);
        }
Example #5
0
        public void Different_Key_In_DynamicComponentDictionary_Returns_Different_Keys()
        {
            using (var session = OpenSession())
            {
                Expression <Func <IEnumerable> > key1 = () => (from a in session.Query <Product>() where a.Properties["Name"] == "val" select a);
                Expression <Func <IEnumerable> > key2 = () => (from a in session.Query <Product>() where a.Properties["Description"] == "val" select a);

                var nhKey1 = new NhLinqExpression(key1.Body, sessions);
                var nhKey2 = new NhLinqExpression(key2.Body, sessions);

                Assert.AreNotEqual(nhKey1.Key, nhKey2.Key);
            }
        }
Example #6
0
        public void Different_OfType_Returns_Different_Keys()
        {
            using (var session = OpenSession())
            {
                Expression <Func <IEnumerable> > ofType1 = () => (from a in session.Query <Animal>().OfType <Cat>() where a.Pregnant select a.Id);
                Expression <Func <IEnumerable> > ofType2 = () => (from a in session.Query <Animal>().OfType <Dog>() where a.Pregnant select a.Id);

                var nhOfType1 = new NhLinqExpression(ofType1.Body, sessions);
                var nhOfType2 = new NhLinqExpression(ofType2.Body, sessions);

                Assert.AreNotEqual(nhOfType1.Key, nhOfType2.Key);
            }
        }
        public static string GenerateSql(this IQueryable queryable, ISession session)
        {
            queryable.ThrowIfNull("this");
            session.ThrowIfNull("session");

            var sessionImplementor = session.GetSessionImplementation();
            var nhLinqExpression   = new NhLinqExpression(queryable.Expression, sessionImplementor.Factory);
            var translatorFactory  = new ASTQueryTranslatorFactory();
            var translators        = translatorFactory.CreateQueryTranslators(nhLinqExpression, null, false,
                                                                              sessionImplementor.EnabledFilters, sessionImplementor.Factory);

            return(translators[0].SQLString);
        }
Example #8
0
        public String ToSql(System.Linq.IQueryable queryable)
        {
            var sessionProperty   = typeof(DefaultQueryProvider).GetProperty("Session", BindingFlags.NonPublic | BindingFlags.Instance);
            var session           = sessionProperty.GetValue(queryable.Provider, null) as ISession;
            var sessionImpl       = session.GetSessionImplementation();
            var factory           = sessionImpl.Factory;
            var nhLinqExpression  = new NhLinqExpression(queryable.Expression, factory);
            var translatorFactory = new ASTQueryTranslatorFactory();
            var translator        = translatorFactory.CreateQueryTranslators(nhLinqExpression, null, false, sessionImpl.EnabledFilters, factory).First();

            //in case you want the parameters as well
            //var parameters = nhLinqExpression.ParameterValuesByName.ToDictionary(x => x.Key, x => x.Value.Item1);

            return(translator.SQLString);
        }
Example #9
0
        public void DifferentKeyInDynamicComponentDictionaryReturnsDifferentExpressionKeys()
        {
            using (var session = OpenSession())
            {
// ReSharper disable AccessToDisposedClosure Ok since the expressions aren't actually used after the using block.
                Expression <Func <IEnumerable> > key1 = () => (from a in session.Query <Product>() where (string)a.Details.Properties["Name"] == "val" select a);
                Expression <Func <IEnumerable> > key2 = () => (from a in session.Query <Product>() where (string)a.Details.Properties["Description"] == "val" select a);
// ReSharper restore AccessToDisposedClosure

                var nhKey1 = new NhLinqExpression(key1.Body, Sfi);
                var nhKey2 = new NhLinqExpression(key2.Body, Sfi);

                Assert.AreNotEqual(nhKey1.Key, nhKey2.Key);
            }
        }
Example #10
0
        public void Different_Key_In_DynamicComponentDictionary_Returns_Different_Keys()
        {
            using (var session = OpenSession())
            {
                // Gets translated to SQL, which does not care about reference comparison vs value comparison.
#pragma warning disable CS0252 // Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'
                Expression <Func <IEnumerable> > key1 = () => (from a in session.Query <Product>() where a.Properties["Name"] == "val" select a);
                Expression <Func <IEnumerable> > key2 = () => (from a in session.Query <Product>() where a.Properties["Description"] == "val" select a);
#pragma warning restore CS0252 // Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'

                var nhKey1 = new NhLinqExpression(key1.Body, Sfi);
                var nhKey2 = new NhLinqExpression(key2.Body, Sfi);

                Assert.AreNotEqual(nhKey1.Key, nhKey2.Key);
            }
        }
Example #11
0
        public void Different_Select_Properties_Return_Different_Keys()
        {
            using (var s = OpenSession())
            {
                var db = new Northwind(s);

                Expression <Func <IEnumerable <string> > > customerId =
                    () => from c in db.Customers select c.CustomerId;
                Expression <Func <IEnumerable <string> > > title =
                    () => from c in db.Customers select c.ContactTitle;

                var nhLondon  = new NhLinqExpression(customerId.Body, sessions);
                var nhNewYork = new NhLinqExpression(title.Body, sessions);

                Assert.AreNotEqual(nhLondon.Key, nhNewYork.Key);
            }
        }
Example #12
0
        public void Different_Conditionals_Return_Different_Keys()
        {
            using (var s = OpenSession())
            {
                var db = new Northwind(s);

                Expression <Func <IEnumerable> > newCustomerId =
                    () => from c in db.Customers select new { Desc = c.CustomerId == "1" ? "First" : "Not First" };
                Expression <Func <IEnumerable> > customerId =
                    () => from c in db.Customers select new { Desc = c.CustomerId != "1" ? "First" : "Not First" };

                var nhLondon  = new NhLinqExpression(newCustomerId.Body, sessions);
                var nhNewYork = new NhLinqExpression(customerId.Body, sessions);

                Assert.AreNotEqual(nhLondon.Key, nhNewYork.Key);
            }
        }
        public string GetGeneratedSql(IQueryable queryable, ISession session)
        {
            var sessionImp        = (ISessionImplementor)session;
            var nhLinqExpression  = new NhLinqExpression(queryable.Expression, sessionImp.Factory);
            var translatorFactory = new ASTQueryTranslatorFactory();
            var translators       = translatorFactory.CreateQueryTranslators(nhLinqExpression, null, false,
                                                                             sessionImp.EnabledFilters, sessionImp.Factory);

            var sql           = translators.First().SQLString;
            var formamttedSql = FormatStyle.Basic.Formatter.Format(sql);
            int i             = 0;
            var map           = ExpressionParameterVisitor.Visit(queryable.Expression, sessionImp.Factory).ToArray();

            formamttedSql = Regex.Replace(formamttedSql, @"\?", m => map[i++].Key.ToString().Replace('"', '\''));

            return(formamttedSql);
        }
Example #14
0
        protected override NhLinqExpression PrepareQuery(Expression expression, out IQuery query)
        {
            // Detect non-sharded NHibernate session
            if (this.Session is SessionImpl)
            {
                return(base.PrepareQuery(expression, out query));
            }

            var linqExpression = new NhLinqExpression(expression, this.Session.Factory);

            query = this.Session.CreateQuery(linqExpression);

            SetParameters(query, linqExpression.ParameterValuesByName);
            SetResultTransformerAndAdditionalCriteria(query, linqExpression, linqExpression.ParameterValuesByName);

            return(linqExpression);
        }
Example #15
0
        public void Different_Select_Member_Initialisation_Returns_Different_Keys()
        {
            using (var s = OpenSession())
            {
                var db = new Northwind(s);

                Expression <Func <IEnumerable> > newCustomerId =
                    () => from c in db.Customers select new { Id = c.CustomerId, Title = c.ContactTitle };
                Expression <Func <IEnumerable> > customerId =
                    () => from c in db.Customers select new { Title = c.ContactTitle, Id = c.CustomerId };

                var nhLondon  = new NhLinqExpression(newCustomerId.Body, sessions);
                var nhNewYork = new NhLinqExpression(customerId.Body, sessions);

                Assert.AreNotEqual(nhLondon.Key, nhNewYork.Key);
            }
        }
Example #16
0
        public void Identical_Expressions_Return_The_Same_Key()
        {
            using (var s = OpenSession())
            {
                var db = new Northwind(s);

                Expression <Func <IEnumerable <Customer> > > london1 =
                    () => from c in db.Customers where c.Address.City == "London" select c;
                Expression <Func <IEnumerable <Customer> > > london2 =
                    () => from c in db.Customers where c.Address.City == "London" select c;

                var nhLondon1 = new NhLinqExpression(london1.Body, sessions);
                var nhLondon2 = new NhLinqExpression(london2.Body, sessions);

                Assert.AreEqual(nhLondon1.Key, nhLondon2.Key);
            }
        }
Example #17
0
        public void Different_Select_Types_Return_Different_Keys()
        {
            using (var s = OpenSession())
            {
                var db = new Northwind(s);

                Expression <Func <IEnumerable> > newCustomerId =
                    () => from c in db.Customers select new { c.CustomerId };
                Expression <Func <IEnumerable> > customerId =
                    () => from c in db.Customers select c.CustomerId;

                var nhLondon  = new NhLinqExpression(newCustomerId.Body, sessions);
                var nhNewYork = new NhLinqExpression(customerId.Body, sessions);

                Assert.AreNotEqual(nhLondon.Key, nhNewYork.Key);
            }
        }
Example #18
0
        public void Different_Where_Clauses_Return_Different_Keys()
        {
            using (var s = OpenSession())
            {
                var db = new Northwind(s);

                Expression <Func <IEnumerable <Customer> > > london =
                    () => from c in db.Customers where c.Address.City == "London" select c;
                Expression <Func <IEnumerable <Customer> > > company =
                    () => from c in db.Customers where c.CompanyName == "Acme" select c;

                var nhLondon  = new NhLinqExpression(london.Body, sessions);
                var nhNewYork = new NhLinqExpression(company.Body, sessions);

                Assert.AreNotEqual(nhLondon.Key, nhNewYork.Key);
            }
        }
Example #19
0
        public void Different_Unary_Operation_Returns_Different_Keys()
        {
            using (var s = OpenSession())
            {
                var db = new Northwind(s);

                Expression <Func <IEnumerable> > newCustomerId =
                    () => from c in db.Customers where c.CustomerId == "1" select c;
                Expression <Func <IEnumerable> > customerId =
                    () => from c in db.Customers where !(c.CustomerId == "1") select c;

                var nhLondon  = new NhLinqExpression(newCustomerId.Body, sessions);
                var nhNewYork = new NhLinqExpression(customerId.Body, sessions);

                Assert.AreNotEqual(nhLondon.Key, nhNewYork.Key);
            }
        }
Example #20
0
        public void Different_Null_Returns_Different_Keys()
        {
            using (var session = OpenSession())
            {
                string nullVariable    = null;
                string notNullVariable = "Hello";

                Expression <Func <IEnumerable> > null1   = () => (from a in session.Query <Animal>() where a.Description == null select a);
                Expression <Func <IEnumerable> > null2   = () => (from a in session.Query <Animal>() where a.Description == nullVariable select a);
                Expression <Func <IEnumerable> > notNull = () => (from a in session.Query <Animal>() where a.Description == notNullVariable select a);

                var nhNull1   = new NhLinqExpression(null1.Body, sessions);
                var nhNull2   = new NhLinqExpression(null2.Body, sessions);
                var nhNotNull = new NhLinqExpression(notNull.Body, sessions);

                Assert.AreNotEqual(nhNull1.Key, nhNotNull.Key);
                Assert.AreNotEqual(nhNull2.Key, nhNotNull.Key);
            }
        }
Example #21
0
        public void Different_Key_In_DynamicComponentDictionary_Returns_Different_Keys()
        {
            using (var session = OpenSession())
            {
                Expression <Func <IEnumerable> > key1 = () =>
                                                        from a in session.Query <Product>()
                                                        where (string)a.Properties["Name"] == "val"
                                                        select a;
                Expression <Func <IEnumerable> > key2 = () =>
                                                        from a in session.Query <Product>()
                                                        where (string)a.Properties["Description"] == "val"
                                                        select a;

                var nhKey1 = new NhLinqExpression(key1.Body, Sfi);
                var nhKey2 = new NhLinqExpression(key2.Body, Sfi);

                Assert.That(nhKey2.Key, Is.Not.EqualTo(nhKey1.Key));
            }
        }
Example #22
0
        private static string PopularParametros(NhLinqExpression nhLinqExpression, string sql)
        {
            try
            {
                var parametros = nhLinqExpression.ParameterValuesByName
                                 .Aggregate(new List <string>(), (lista, item) =>
                {
                    var valor = item.Value.Item1;

                    var listaValor = (valor as IList);
                    if (listaValor == null)
                    {
                        listaValor = new[] { valor }
                    }
                    ;

                    valor = string.Join(
                        ',',
                        listaValor
                        .OfType <dynamic>()
                        .Select(s => FormartarValor(s))
                        .ToArray());

                    lista.Add(valor.ToString());

                    return(lista);
                })
                                 .ToArray();

                int i       = 0;
                var retorno = Regex.Replace(
                    sql,
                    @"\?",
                    r => parametros[i++]);

                return(retorno);
            }
            catch
            {
                return(sql);
            }
        }
Example #23
0
        public void Expressions_Differing_Only_By_Constants_Return_The_Same_Key()
        {
            using (var s = OpenSession())
            {
                var db = new Northwind(s);

                Expression <Func <IEnumerable <Customer> > > london =
                    () => from c in db.Customers where c.Address.City == "London" select c;

                Expression <Func <IEnumerable <Customer> > > newYork =
                    () => from c in db.Customers where c.Address.City == "New York" select c;

                var nhLondon  = new NhLinqExpression(london.Body, sessions);
                var nhNewYork = new NhLinqExpression(newYork.Body, sessions);

                Assert.AreEqual(nhLondon.Key, nhNewYork.Key);
                Assert.AreEqual(1, nhLondon.ParameterValuesByName.Count);
                Assert.AreEqual(1, nhNewYork.ParameterValuesByName.Count);
                Assert.AreEqual("London", nhLondon.ParameterValuesByName.First().Value.Item1);
                Assert.AreEqual("New York", nhNewYork.ParameterValuesByName.First().Value.Item1);
            }
        }
Example #24
0
        public override object ExecuteFuture(Expression expression)
        {
            ISession session = holder.CreateSession(targetType);

            try
            {
                IQuery           query;
                NhLinqExpression nhQuery;
                NhLinqExpression nhLinqExpression = PrepareQuery(expression, session.GetSessionImplementation(), out query, out nhQuery);
                return(ExecuteFutureQuery(nhLinqExpression, query, nhQuery));
            }
            catch (Exception ex)
            {
                holder.FailSession(session);

                throw new ActiveRecordException("Cold not execute linq query for " + targetType.Name, ex);
            }
            finally
            {
                holder.ReleaseSession(session);
            }
        }
Example #25
0
        // <summary>
        /// Retorna o SQL da query informada
        /// </summary>
        /// <param name="session"/>
        /// <param name="queryable"/>
        /// <returns><see cref="string"/></returns>
        public static string GetSql(this NHibernate.ISession session, IQueryable queryable)
        {
            var sessionImpl = session as NHibernate.Impl.SessionImpl;

            var nhLinqExpression = new NhLinqExpression(
                queryable.Expression,
                sessionImpl.Factory);

            var queryTranslatorImpl = new ASTQueryTranslatorFactory()
                                      .CreateQueryTranslators(
                nhLinqExpression,
                null,
                false,
                sessionImpl.EnabledFilters,
                sessionImpl.Factory)
                                      .First() as QueryTranslatorImpl;

            var retorno = PopularParametros(
                nhLinqExpression,
                FormatStyle.Basic.Formatter.Format(queryTranslatorImpl.SQLString));

            return(retorno);
        }
Example #26
0
        public void CanSpecifyParameterTypeInfo()
        {
            using (var s = OpenSession())
            {
                var db = new Northwind(s);

                Expression <Func <IEnumerable <Customer> > > london =
                    () => from c in db.Customers where c.Address.City == "London".MappedAs(NHibernateUtil.StringClob) select c;

                Expression <Func <IEnumerable <Customer> > > newYork =
                    () => from c in db.Customers where c.Address.City == "New York".MappedAs(NHibernateUtil.AnsiString) select c;

                var nhLondon  = new NhLinqExpression(london.Body, sessions);
                var nhNewYork = new NhLinqExpression(newYork.Body, sessions);

                var londonParameter = nhLondon.ParameterValuesByName.Single().Value;
                Assert.That(londonParameter.Item1, Is.EqualTo("London"));
                Assert.That(londonParameter.Item2, Is.EqualTo(NHibernateUtil.StringClob));

                var newYorkParameter = nhNewYork.ParameterValuesByName.Single().Value;
                Assert.That(newYorkParameter.Item1, Is.EqualTo("New York"));
                Assert.That(newYorkParameter.Item2, Is.EqualTo(NHibernateUtil.AnsiString));
            }
        }
Example #27
0
 public void SetResultTransformerAndAdditionalCriteria(IQuery query, NhLinqExpression nhExpression, IDictionary <string, Tuple <object, IType> > parameters)
 {
     throw new NotImplementedException();
 }
Example #28
0
 public void SetResultTransformerAndAdditionalCriteria(IQuery query, NhLinqExpression nhExpression, IDictionary <string, Tuple <object, IType> > parameters)
 {
     _queryProvider.SetResultTransformerAndAdditionalCriteria(query, nhExpression, parameters);
 }