public static ISession CreateTemporaryIdTable <T>(this ISession session, string tableName, T[] values)
        {
            if (!tableName.StartsWith("#"))
            {
                tableName = "#" + tableName;
            }

            SqlType type;

            try
            {
                type = ((NullableType)NHibernateUtil.GuessType(values.First())).SqlType;
            }
            catch (Exception exception)
            {
                throw new ArgumentException($"Unsupported type \"{values.First().GetType().FullName}\" for values argument");
            }

            var sqlType = session.GetSessionImplementation().Factory.Dialect.GetTypeName(type);

            session.CreateSQLQuery($"CREATE TABLE {tableName} (Id {sqlType} NOT NULL PRIMARY KEY);").ExecuteUpdate();

            foreach (var value in values)
            {
                session.CreateSQLQuery($"INSERT INTO {tableName} (Id) VALUES (:Id);").SetParameter("Id", value).ExecuteUpdate();
            }

            return(session);
        }
        public MsSql2012GeometryDialect()
        {
            IType type = NHibernateUtil.GuessType(typeof(Guid));
            SQLFunctionTemplate template = new SQLFunctionTemplate(type, "NEWID()");

            RegisterFunction("guid", template);
        }
示例#3
0
        protected static IProjection ProcessEnd <T>(MemberExpression memberExpression)
        {
            var parentExpression = memberExpression.Expression;
            var projection       = ProjectionWrapper.FindMemberProjection(parentExpression);

            return(Projections.SqlFunction("upper", NHibernateUtil.GuessType(typeof(T)), projection));
        }
示例#4
0
        public static TypedValue[] GetTypedValues(ICriteriaQuery criteriaQuery, ICriteria criteria,
                                                  IProjection projection,
                                                  string propertyName,
                                                  params object[] values)
        {
            List <TypedValue> types = new List <TypedValue>();
            var propertyProjection  = projection as IPropertyProjection;

            if (projection == null || propertyProjection != null)
            {
                var pn = propertyProjection != null ? propertyProjection.PropertyName : propertyName;
                foreach (object value in values)
                {
                    TypedValue typedValue = criteriaQuery.GetTypedValue(criteria, pn, value);
                    types.Add(typedValue);
                }
            }
            else
            {
                foreach (object value in values)
                {
                    types.Add(new TypedValue(NHibernateUtil.GuessType((object)value), value, EntityMode.Poco));
                }
            }
            return(types.ToArray());
        }
        /// <summary>
        /// Write an instance of the mapped class to a prepared statement.
        /// Implementors should handle possibility of null values.
        /// A multi-column type should be written to parameters starting from index.
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="value"></param>
        /// <param name="index"></param>
        /// <param name="session"></param>
        public void NullSafeSet(IDbCommand cmd, object value, int index, bool[] settable, ISessionImplementor session)
        {
            if (value == null)
            {
                return;
            }

            var propIndex = index;

            foreach (var t in _properties)
            {
                try
                {
                    var property   = t;
                    var valueToSet = property.PropertyType == value.GetType() ? value : property.GetValue(value, null);
                    NHibernateUtil.GuessType(property.PropertyType).NullSafeSet(cmd, valueToSet, propIndex, settable,
                                                                                session);
                    propIndex++;
                }
                catch (Exception e)
                {
                    LogHelper.Warn <CompositeUserTypeBase <T> >("Error handling null setters.{0}{1}{0}{2}",
                                                                Environment.NewLine, e.Message, e);
                    throw;
                }
            }
        }
示例#6
0
        /// <summary>
        /// Convert Scalar
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private IDictionary <string, IType> ConvertTypeScalar(Type type)
        {
            IDictionary <string, IType> scalars = null;
            var cacheKey = string.Format("{0}{1}", "TYPESCALARS_", type.FullName);

            if (CacheManager.MemoryCacheManager.Contains(cacheKey))
            {
                scalars = CacheManager.MemoryCacheManager.Get(cacheKey) as IDictionary <string, IType>;
            }
            else
            {
                scalars = new Dictionary <string, IType>();
                if (!type.IsValueType && type != typeof(string))
                {
                    type.GetProperties()
                    .ToList()
                    .ForEach(p =>
                    {
                        if (p.GetCustomAttribute <IgnoreConvertTypeScalarAttribute>() == null)
                        {
                            scalars.Add(p.Name, NHibernateUtil.GuessType(p.PropertyType));
                        }
                    });
                }
                CacheManager.MemoryCacheManager.Set(cacheKey, scalars, CacheExpirationTypeEnum.None, null);
            }

            return(scalars);
        }
        public void CanGuessTypeOfNullableInt32ByValue()
        {
            int?val = 15;

            Assert.AreEqual(NHibernateUtil.Int32,
                            NHibernateUtil.GuessType(val));
        }
        protected override Expression VisitConstantExpression(ConstantExpression expression)
        {
            if (!_parameters.ContainsKey(expression) && !typeof(IQueryable).IsAssignableFrom(expression.Type) && !IsNullObject(expression))
            {
                // We use null for the type to indicate that the caller should let HQL figure it out.
                object value = expression.Value;
                IType  type  = null;

                // We have a bit more information about the null parameter value.
                // Figure out a type so that HQL doesn't break on the null. (Related to NH-2430)
                if (expression.Value == null)
                {
                    type = NHibernateUtil.GuessType(expression.Type);
                }

                // Constant characters should be sent as strings
                if (expression.Type == typeof(char))
                {
                    value = value.ToString();
                }

                // There is more information available in the Linq expression than to HQL directly.
                // In some cases it might be advantageous to use the extra info.  Assuming this
                // comes up, it would be nice to combine the HQL parameter type determination code
                // and the Expression information.

                _parameters.Add(expression, new NamedParameter("p" + (_parameters.Count + 1), value, type));
            }

            return(base.VisitConstantExpression(expression));
        }
示例#9
0
        public static ISQLFunction RegisterFunction <T>(this ISessionFactory factory, String name, String sql)
        {
            IType        type     = NHibernateUtil.GuessType(typeof(T));
            ISQLFunction function = new SQLFunctionTemplate(type, sql);

            RegisterFunction(factory, name, function);
            return(function);
        }
示例#10
0
        public StatusTaskMap()
        {
            Table("StatusTask");
            Id(x => x.Id, map =>
            {
                map.Column("Id");
                map.Generator(Generators.Identity);
                map.Type((IIdentifierType)TypeFactory.Basic(typeof(int).FullName));
                map.UnsavedValue(0);
            });
            Property(x => x.StartRun, map =>
            {
                map.NotNullable(true);
                map.Type(TypeFactory.Basic(typeof(DateTime).FullName));
            });
            Property(x => x.Error, map =>
            {
                map.NotNullable(false);
                map.Type(TypeFactory.Basic(typeof(string).FullName));
            });
            Property(x => x.TotalRows, map =>
            {
                map.NotNullable(false);
                map.Type(TypeFactory.Basic(typeof(int?).FullName));
            });
            Property(x => x.ErrorRows, map =>
            {
                map.NotNullable(false);
                map.Type(TypeFactory.Basic(typeof(int?).FullName));
            });

            Property(x => x.EndRun, map =>
            {
                map.NotNullable(false);
                map.Type(TypeFactory.Basic(typeof(DateTime?).FullName));
            });
            Property(x => x.TaskExecType, map =>
            {
                map.NotNullable(true);
                map.Type(NHibernateUtil.
                         GuessType(
                             typeof(
                                 TaskExecType
                                 )));
            });
            ManyToOne(x => x.Sheduler, map =>
            {
                map.Cascade(Cascade.None);
                map.Class(typeof(Sheduler));
                map.Column("IdShedule");
                map.Lazy(LazyRelation.Proxy);
                map.NotNullable(false);
            });
        }
        static IType GetNHibernateType <TYPE>()
        {
            // No default constructor on String, so...
            if (typeof(TYPE) == typeof(String))
            {
                return(NHibernateUtil.String);
            }
            var inst = Activator.CreateInstance <TYPE>();

            return(NHibernateUtil.GuessType(inst));
        }
示例#12
0
文件: Fixture.cs 项目: jrauber/GH1429
 public async Task CanMinProjectionOnIdentityProjectionAsync()
 {
     using (ISession s = OpenSession())
     {
         ISQLFunction arithmaticAddition = new VarArgsSQLFunction("(", "+", ")");
         ICriteria    c =
             s.CreateCriteria(typeof(Person)).SetProjection(
                 Projections.Min(Projections.SqlFunction(arithmaticAddition, NHibernateUtil.GuessType(typeof(double)),
                                                         Projections.Property("IQ"), Projections.Property("ShoeSize"))));
         IList list = await(c.ListAsync());
         Assert.AreEqual(19, list[0]);
     }
 }
示例#13
0
 public void CanAvgProjectionOnSqlFunction()
 {
     using (ISession s = OpenSession())
     {
         ISQLFunction arithmaticAddition = new VarArgsSQLFunction("(", "+", ")");
         ICriteria    c =
             s.CreateCriteria(typeof(Person)).SetProjection(
                 Projections.Avg(Projections.SqlFunction(arithmaticAddition, NHibernateUtil.GuessType(typeof(double)),
                                                         Projections.Property("IQ"), Projections.Property("ShoeSize"))));
         IList list = c.List();
         Assert.AreEqual(((double)334) / 5, list[0]);
     }
 }
示例#14
0
        public static TypedValue GetTypedValue(
            ICriteriaQuery criteriaQuery,
            ICriteria criteria,
            IProjection projection,
            string propertyName,
            object value)
        {
            if (propertyName != null || (propertyName = (projection as IPropertyProjection)?.PropertyName) != null)
            {
                return(criteriaQuery.GetTypedValue(criteria, propertyName, value));
            }

            return(new TypedValue(NHibernateUtil.GuessType(value), value));
        }
        protected override Expression VisitConstant(ConstantExpression expression)
        {
            if (!_parameters.ContainsKey(expression) && !typeof(IQueryable).IsAssignableFrom(expression.Type) && !IsNullObject(expression))
            {
                // We use null for the type to indicate that the caller should let HQL figure it out.
                object value = expression.Value;
                IType  type  = null;

                // We have a bit more information about the null parameter value.
                // Figure out a type so that HQL doesn't break on the null. (Related to NH-2430)
                // In v5.3 types are calculated by ParameterTypeLocator, this logic is only for back compatibility.
                // TODO 6.0: Remove
                if (expression.Value == null)
                {
                    type = NHibernateUtil.GuessType(expression.Type);
                }

                // Constant characters should be sent as strings
                // TODO 6.0: Remove
                if (_queryVariables == null && expression.Type == typeof(char))
                {
                    value = value.ToString();
                }

                // There is more information available in the Linq expression than to HQL directly.
                // In some cases it might be advantageous to use the extra info.  Assuming this
                // comes up, it would be nice to combine the HQL parameter type determination code
                // and the Expression information.

                NamedParameter parameter = null;
                if (_queryVariables != null &&
                    _queryVariables.TryGetValue(expression, out var variable) &&
                    !_variableParameters.TryGetValue(variable, out parameter))
                {
                    parameter = CreateParameter(expression, value, type);
                    _variableParameters.Add(variable, parameter);
                }

                if (parameter == null)
                {
                    parameter = CreateParameter(expression, value, type);
                }

                _parameters.Add(expression, parameter);

                return(base.VisitConstant(expression));
            }

            return(base.VisitConstant(expression));
        }
示例#16
0
        public override void VisitConvertExpression(UnaryExpression expr)
        {
            var visitor = new SelectArgumentsVisitor <TResult>(parent);

            visitor.VisitExpression(expr.Operand);
            var list = NHibernate.Expressions.Projections.ProjectionList();

            foreach (var proj in visitor.Projections)
            {
                list.Add(proj);
            }
            var projection = new CastProjection(NHibernateUtil.GuessType(expr.Type), list);

            projections.Add(projection);
        }
        private static ICacheAssembler[] GuessTypes(IList cacheable)
        {
            var firstRow    = cacheable[0];
            var colCount    = (cacheable[0] as object[])?.Length ?? 1;
            var returnTypes = new ICacheAssembler[colCount];

            if (colCount == 1)
            {
                foreach (var obj in cacheable)
                {
                    if (obj == null)
                    {
                        continue;
                    }
                    returnTypes[0] = NHibernateUtil.GuessType(obj);
                    break;
                }
            }
            else
            {
                var foundTypes = 0;
                foreach (object[] row in cacheable)
                {
                    for (var i = 0; i < colCount; i++)
                    {
                        if (row[i] != null && returnTypes[i] == null)
                        {
                            returnTypes[i] = NHibernateUtil.GuessType(row[i]);
                            foundTypes++;
                        }
                    }
                    if (foundTypes == colCount)
                    {
                        break;
                    }
                }
            }
            // If a column value was null for all rows, its type is still null: put a type which will just yield null
            // on null value.
            for (var i = 0; i < colCount; i++)
            {
                if (returnTypes[i] == null)
                {
                    returnTypes[i] = NHibernateUtil.String;
                }
            }
            return(returnTypes);
        }
        /// <summary>
        /// Retrieve an instance of the mapped class from a IDataReader. Implementors
        /// should handle possibility of null values.
        /// </summary>
        /// <param name="dr">IDataReader</param>
        /// <param name="names">the column names</param>
        /// <param name="session"></param>
        /// <param name="owner">the containing entity</param>
        /// <returns>
        /// </returns>
        public object NullSafeGet(IDataReader dr, string[] names, ISessionImplementor session, object owner)
        {
            if (dr == null)
            {
                return(null);
            }

            var values = new object[names.Length];

            for (var i = 0; i < names.Length; i++)
            {
                values[i] = NHibernateUtil.GuessType(_properties[i].PropertyType)
                            .NullSafeGet(dr, names[i], session, owner);
            }
            return(CreateInstance(values));
        }
示例#19
0
        public void AvgTest()
        {
            ISession    session    = factory.OpenSession();
            IProjection expression = Projections.Avg("Pay");

            CreateObjects(typeof(Simple), session);
            IType nhType = NHibernateUtil.GuessType(typeof(double));

            SqlType[] sqlTypes      = nhType.SqlTypes(this.factoryImpl);
            string    sqlTypeString = factoryImpl.Dialect.GetCastTypeName(sqlTypes[0]);
            SqlString sqlString     = expression.ToSqlString(criteria, 0, criteriaQuery);
            string    expectedSql   = string.Format("avg(cast(sql_alias.Pay as {0})) as y0_", sqlTypeString);

            CompareSqlStrings(sqlString, expectedSql, 0);
            session.Close();
        }
示例#20
0
        /// <summary>
        /// Write an instance of the mapped class to a prepared statement.
        /// Implementors should handle possibility of null values.
        /// A multi-column type should be written to parameters starting from index.
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="value"></param>
        /// <param name="index"></param>
        /// <param name="session"></param>
        public void NullSafeSet(IDbCommand cmd, object value, int index, ISessionImplementor session)
        {
            if (value == null)
            {
                return;
            }

            var propIndex = index;

            for (var i = 0; i < _properties.Count; i++)
            {
                var property  = _properties[i];
                var propValue = property.GetValue(value, null);
                NHibernateUtil.GuessType(property.PropertyType).NullSafeSet(cmd, propValue, propIndex, session);
                propIndex++;
            }
        }
示例#21
0
文件: Fixture.cs 项目: jrauber/GH1429
        public void CanOrderBySqlProjectionDesc()
        {
            using (ISession s = OpenSession())
            {
                ISQLFunction arithmaticAddition = new VarArgsSQLFunction("(", "+", ")");
                ICriteria    c =
                    s.CreateCriteria(typeof(Person)).AddOrder(
                        Order.Desc(Projections.SqlFunction(arithmaticAddition, NHibernateUtil.GuessType(typeof(double)),
                                                           Projections.Property("IQ"), Projections.Property("ShoeSize"))));
                IList <Person> list = c.List <Person>();

                for (int i = 0; i < list.Count - 1; i++)
                {
                    Assert.IsTrue(list[i].IQ + list[i].ShoeSize >= list[i + 1].IQ + list[i + 1].ShoeSize);
                }
            }
        }
        /// <inheritdoc />
        public override IProjection Project
        (
            Expression expression,
            HelperContext context
        )
        {
            string operation = GetArithmeticOperation(expression.NodeType);

            var binary = (BinaryExpression)expression;

            return(new SqlFunctionProjection
                   (
                       new VarArgsSQLFunction("(", operation, ")"),
                       NHibernateUtil.GuessType(binary.Left.Type),
                       ProjectionHelper.GetProjection(binary.Left, context),
                       ProjectionHelper.GetProjection(binary.Right, context)
                   ));
        }
        protected override Expression VisitUnary(UnaryExpression expr)
        {
            if (expr.NodeType == ExpressionType.Convert)
            {
                var visitor = new SelectArgumentsVisitor(_rootCriteria, _session);
                visitor.Visit(expr.Operand);

                ProjectionList list = NHProjections.ProjectionList();
                foreach (IProjection proj in visitor._projections)
                {
                    list.Add(proj);
                }

                var projection = new CastProjection(NHibernateUtil.GuessType(expr.Type), list);
                _projections.Add(projection);
            }

            return(expr);
        }
示例#24
0
 public void NullSafeSet(DbCommand cmd, object value, int index, ISessionImplementor session)
 {
     if (value == null)
     {
         cmd.Parameters[index].Value = DBNull.Value;
         return;
     }
     if (value is IStrongTypeId stValue)
     {
         var realValue = stValue.GetValue();
         var nhType    = NHibernateUtil.GuessType(realValue);
         nhType.NullSafeSet(cmd, realValue, index, session);
     }
     else
     {
         var nhType = NHibernateUtil.GuessType(value);
         nhType.NullSafeSet(cmd, value, index, session);
     }
 }
示例#25
0
        public static IQuery ApplyParameters(this IQuery query, QueryParameters queryParams)
        {
            if (queryParams != null)
            {
                foreach (QueryParameter qp in queryParams)
                {
                    NHibernate.Type.IType type;
                    if (qp.Type.IsAssignableFrom(typeof(bool)))
                    {
                        type = NHibernateUtil.Boolean;
                    }
                    else
                    {
                        type = NHibernateUtil.GuessType(qp.Type);
                    }

                    query.SetParameter(qp.Name, qp.Value, type);
                }
            }
            return(query);
        }
示例#26
0
 public MonthlyFrequencyMap()
 {
     Lazy(false);
     DiscriminatorValue("monthly");
     Join("Frequency", join =>
     {
         join.Table("MonthlyFrequency");
         join.Key(x =>
         {
             x.Column("Frequency");
             x.NotNullable(true);
             x.Unique(true);
             x.ForeignKey("FK_MontlyFrequency_SheduleFrequency");
         });
         join.Property(x => x.DayOffset, map =>
         {
             map.Column("DayNumber");
             map.NotNullable(false);
             map.Access(Accessor.Field);
             map.Type(
                 TypeFactory.Basic(
                     typeof(int?).FullName));
         });
         join.Property(x => x.WeekNumber, map =>
         {
             map.NotNullable(false);
             map.Type(
                 NHibernateUtil.GuessType(
                     typeof(RhythmByWeek?)));
         });
         join.Property(x => x.Week, map =>
         {
             map.NotNullable(false);
             map.Type(
                 NHibernateUtil.GuessType(
                     typeof(DayOfWeek?)));
         });
     });
 }
示例#27
0
 public virtual void Delete(TKey key)
 {
     this.Delete(SqlParameterWrapperCollection.Empty.Add("oid", key, NHibernateUtil.GuessType(typeof(TKey))));
 }
示例#28
0
 public ConstantProjection(object value) : this(value, NHibernateUtil.GuessType(value.GetType()))
 {
 }
        /// <summary>
        /// Retrieves the projection for the expression
        /// </summary>
        public static ProjectionInfo FindMemberProjection(Expression expression)
        {
            if (!IsMemberExpression(expression))
            {
                return(AsArithmeticProjection(expression)
                       ?? ProjectionInfo.ForProjection(Projections.Constant(FindValue(expression), NHibernateUtil.GuessType(expression.Type))));
            }

            var unwrapExpression = UnwrapConvertExpression(expression);

            if (unwrapExpression != null)
            {
                return(FindMemberProjection(unwrapExpression));
            }

            var methodCallExpression = expression as MethodCallExpression;

            if (methodCallExpression != null)
            {
                var signature = Signature(methodCallExpression.Method);
                Func <Expression, IProjection> processor;
                if (_customProjectionProcessors.TryGetValue(signature, out processor))
                {
                    return(ProjectionInfo.ForProjection(processor(methodCallExpression)));
                }
            }
            var memberExpression = expression as MemberExpression;

            if (memberExpression != null)
            {
                var signature = Signature(memberExpression.Member);
                Func <Expression, IProjection> processor;
                if (_customProjectionProcessors.TryGetValue(signature, out processor))
                {
                    return(ProjectionInfo.ForProjection(processor(memberExpression)));
                }
            }

            return(ProjectionInfo.ForProperty(FindMemberExpression(expression)));
        }
示例#30
0
 public TKey DeleteAndReturnKey(TKey key)
 {
     return(this.DeleteAndReturnKey(SqlParameterWrapperCollection.Empty.Add("oid", key, NHibernateUtil.GuessType(typeof(TKey)))));
 }