Пример #1
0
		public static string GetVariableType(DbType dbType, bool isNullableColumn)
		{
			string variableType = GetVariableType(dbType);
			if (isNullableColumn && Utility.IsNullableDbType(dbType))
				variableType = variableType + "?";
			return variableType;
		}
Пример #2
0
        /// <summary>
        /// 将C#值转成数据库能存储的值
        /// </summary>
        /// <param name="valu"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public object ParamConvertValue(object valu, DbType type)
        {
            if (valu == null) { return null; }

            // 时间类型转换
            if (type == DbType.DateTime)
            {
                DateTime dtValue; DateTime.TryParse(valu.ToString(), out dtValue);
                if (dtValue == DateTime.MinValue) { valu = new DateTime(1900, 1, 1); }
            }
            // 枚举类型转换
            if (valu is Enum) { valu = Convert.ToInt32(valu); }

            // List类型转换成字符串并以,分隔
            if (valu.GetType().IsGenericType)
            {
                var sb = new StringBuilder();
                // list类型
                if (valu.GetType().GetGenericTypeDefinition() != typeof(Nullable<>))
                {
                    var enumerator = ((IEnumerable)valu).GetEnumerator();
                    while (enumerator.MoveNext()) { sb.Append(enumerator.Current + ","); }
                }
                else
                {
                    if (valu.GetType().GetGenericArguments()[0] == typeof(int))
                    {
                        var enumerator = ((IEnumerable<int?>)valu).GetEnumerator();
                        while (enumerator.MoveNext()) { sb.Append(enumerator.Current.GetValueOrDefault() + ","); }
                    }
                }
                valu = sb.Length > 0 ? sb.Remove(sb.Length - 1, 1).ToString() : "";
            }
            return valu;
        }
Пример #3
0
 public string DbTypeToString(DbType type, int? length)
 {
     string ret;
     if (TypesAsStrings.TryGetValue(type, out ret))
         return ret;
     throw new NotImplementedException(Enum.GetName(typeof(DbType), type));
 }
Пример #4
0
		private static string GetVariableType(DbType dbType)
		{
			switch (dbType) {
				case DbType.AnsiString:
				case DbType.AnsiStringFixedLength:
				case DbType.String:
				case DbType.StringFixedLength: return "string";

				case DbType.Binary:		return "byte[]";
				case DbType.Boolean:	return "bool";
				case DbType.Byte:		return "byte";

				case DbType.Currency:
				case DbType.Decimal:
				case DbType.VarNumeric:	return "decimal";

				case DbType.Date:
				case DbType.DateTime:	return "DateTime";

				case DbType.Double:		return "double";
				case DbType.Guid:		return "Guid";
				case DbType.Int16:		return "short";
				case DbType.Int32:		return "int";
				case DbType.Int64:		return "long";
				case DbType.Object:		return "object";
				case DbType.SByte:		return "sbyte";
				case DbType.Single:		return "float";
				case DbType.Time:		return "TimeSpan";
				case DbType.UInt16:		return "ushort";
				case DbType.UInt32:		return "uint";
				case DbType.UInt64:		return "ulong";

				default:				return "string";
			}
		}
Пример #5
0
 protected CouchBase(string username, string password, AuthenticationType aT, DbType dbType)
 {
     this.username = username;
     this.password = password;
     this.authType = aT;
     this.dbType = dbType;
 }
Пример #6
0
        public virtual DbParameter AddParameter(DbCommand dm, string name, DbType dbType, int size,
            ParameterDirection direction, bool nullable, byte precision, byte scale, string sourceColumn,
            DataRowVersion sourceVersion, object value)
        {
            ////if (dbType == DbType.String)
            ////    throw new Exception("请不要使用DbType.String进行数据库查询!");

            if (CheckInjectAttackForSp(dm, value))
                throw new Exception("输入的部分内容可能对系统稳定性造成影响,操作已停止![" + value + "]");

            DbParameter param = this.ProviderFactory.CreateParameter();
            if (param != null)
            {
                param.ParameterName = name;
                param.DbType = dbType;
                param.Size = size;
                param.Value = value ?? DBNull.Value;
                param.Direction = direction;
                param.IsNullable = nullable;
                param.SourceColumn = sourceColumn;
                param.SourceVersion = sourceVersion;
                dm.Parameters.Add(param);
            }
            return param;
        }
Пример #7
0
 public static bool ContainsRule(Csla.Core.BusinessBase obj, DbType type, string propertyName)
 {
     switch (type)
     {
         case DbType.Int16:
         case DbType.Int32:
         case DbType.Int64:
             return obj.BrokenRulesCollection.Any(
                  brokenRule => brokenRule.RuleName == string.Format("rule://epiworx.core.validation.integerrequired/{0}", propertyName))
                     || obj.BrokenRulesCollection.Any(
                         brokenRule => brokenRule.RuleName == string.Format("rule://csla.rules.commonrules.dataannotation/{0}?a=Epiworx.Core.Validation.IntegerRequiredAttribute", propertyName));
         case DbType.Decimal:
             return obj.BrokenRulesCollection.Any(
                 brokenRule => brokenRule.RuleName == string.Format("rule://epiworx.core.validation.decimalrequired/{0}", propertyName));
         case DbType.Date:
             return obj.BrokenRulesCollection.Any(
               brokenRule => brokenRule.RuleName == string.Format("rule://epiworx.core.validation.daterequired/{0}", propertyName));
         case DbType.DateTime:
             return obj.BrokenRulesCollection.Any(
               brokenRule => brokenRule.RuleName == string.Format("rule://epiworx.core.validation.datetimerequired/{0}", propertyName));
         case DbType.String:
         case DbType.StringFixedLength:
             return obj.BrokenRulesCollection.Any(
              brokenRule => brokenRule.RuleName == string.Format("rule://epiworx.core.validation.stringrequired/{0}", propertyName));
         default:
             throw new NotSupportedException();
     }
 }
Пример #8
0
        /// <summary>
        /// Initialises a new instance of the <see cref="ColumnInfo"/> class.
        /// </summary>
        /// <param name="columnName">The name of the column in the database table.</param>
        /// <param name="dbType">The <see cref="DbType"/> of the column in the database table.</param>
        /// <param name="propertyInfo">The property info for the property the column maps to.</param>
        /// <param name="isIdentifier">A value indicating whether column is the table identifier column (primary key).</param>
        /// <param name="allowInsert">true if the column can be inserted, otherwise false.</param>
        /// <param name="allowUpdate">true if the column can be updated, otherwise false.</param>
        /// <param name="sequenceName">The name of the sequence which generates the identifier value or null if sequences are not used.</param>
        /// <exception cref="ArgumentNullException">Thrown if columnName or propertyInfo are null.</exception>
        public ColumnInfo(
            string columnName,
            DbType dbType,
            PropertyInfo propertyInfo,
            bool isIdentifier,
            bool allowInsert,
            bool allowUpdate,
            string sequenceName)
        {
            if (columnName == null)
            {
                throw new ArgumentNullException("columnName");
            }

            if (propertyInfo == null)
            {
                throw new ArgumentNullException("propertyInfo");
            }

            this.columnName = columnName;
            this.dbType = dbType;
            this.propertyInfo = propertyInfo;
            this.isIdentifier = isIdentifier;
            this.allowInsert = allowInsert;
            this.allowUpdate = allowUpdate;
            this.sequenceName = sequenceName;
        }
Пример #9
0
        protected override string TypeName(DbType type) {
            switch (type) {
                case DbType.Binary:
                    return "bit";

                case DbType.Boolean:
                    return "smallint unsigned";

                case DbType.Byte:
                    return "smallint unsigned";

                case DbType.DateTime:
                case DbType.DateTime2:
                    return "timestamp";

                case DbType.DateTimeOffset:
                    return "timestamptz";

                case DbType.Double:
                    return "double precision";

                default:
                    return base.TypeName(type);
            }
        }
 public EntityParameter(string parameterName, DbType dbType, int size, string sourceColumn)
 {
     SetParameterNameWithValidation(parameterName, "parameterName");
     DbType = dbType;
     Size = size;
     SourceColumn = sourceColumn;
 }
Пример #11
0
 /// <summary>
 /// Constructs a VarArgsSQLFunction instance with a 'static' return type.  An example of a 'static'
 /// return type would be something like an <code>UPPER</code> function which is always returning
 /// a SQL VARCHAR and thus a string type.
 /// </summary>
 /// <param name="registeredType">the return type</param>
 /// <param name="begin">the beginning of the function templating</param>
 /// <param name="sep">the separator for each individual function argument</param>
 /// <param name="end">the end of the function templating</param>
 public VarArgsSQLFunction(DbType registeredType, String begin, String sep, String end)
 {
     this.registeredType = registeredType;
     this.begin = begin;
     this.sep = sep;
     this.end = end;
 }
Пример #12
0
 public void CreateAndCacheDbCommandParameters(string sqlCommandText,
                                               DbCommand command,
                                               string[] paramNames,
                                               DbType[] paramDbTypes,
                                               object[] paramValues) 
 {
     lock (lockObject)
     {
         if (this.ParameterCache.IsCache(sqlCommandText))
         {
             this.ParameterCache.AddParametersFromCache(sqlCommandText, command, paramDbTypes, paramValues);
         }
         else
         {
             if (this.ParameterCache.IsCache(sqlCommandText))
             {
                 this.ParameterCache.AddParametersFromCache(sqlCommandText, command, paramDbTypes, paramValues);
             }
             else
             {
                 this.ParameterCache.CreateAndCacheParameters(sqlCommandText, command, paramNames, paramDbTypes, paramValues);
             }
         }
     }
 }
Пример #13
0
 public DBMapping(string first, string second, DbType type, int size)
 {
     this._first = first;
     this._second = second;
     this._type = type;
     this._size = size;
 }
Пример #14
0
 public Parameters(string Name, object Value, ParameterDirection Direction)
 {
     ParamName = Name;
     ParamValue = Value;
     ParamDbType = DbType.Object;
     ParamDirection = Direction;
 }
Пример #15
0
 public Parameters(string Name, object Value,DbType dbType)
 {
     ParamName = Name;
     ParamValue = Value;
     ParamDbType = dbType;
     ParamDirection = ParameterDirection.Input;
 }
Пример #16
0
 public Parameter(String parameterName, DbType dbtype)
 {
     _parameterName = parameterName;
     _value = DBNull.Value;
     _dbType = dbtype;
     _sourceVersion = DataRowVersion.Default;
 }
Пример #17
0
 public static void AreEqual(string parameterName, object value, DbType dbType, SqlParameter actual)
 {
     Assert.IsNotNull(actual, "Parameter should not be null.");
     Assert.AreEqual(parameterName, actual.ParameterName, "ParameterName");
     Assert.AreEqual(value, actual.Value, "Value");
     Assert.AreEqual(dbType, actual.DbType, "DbType");
 }
Пример #18
0
 public SqlParameter(SqlStatement sqlStatement, object value, DbType dbType, string name)
 {
     this.Parent = sqlStatement ;
     this.value = value;
     this.dbType = dbType;
     this.name = name;
 }
 public FakeDataParameter(DbType dbType, 
     string parameterName, object value)
     : this(dbType, 
     ParameterDirection.Input, true, null, null, 
     DataRowVersion.Current, value)
 {
 }
Пример #20
0
 public void Add(string name, DbType type)
 {
     DbParameter parameter = Command.CreateParameter();
     parameter.ParameterName = string.Format("{0}{1}", ParameterPrefix, name);
     parameter.DbType = type;
     Command.Parameters.Add(parameter);
 }
Пример #21
0
 public DbParameterHelper(DbType type, string name, object value, ParameterDirection direction)
 {
     DbType = type;
     Name = name;
     Value = value;
     Direction = direction;
 }
Пример #22
0
 internal static void TryDetermineSubQueryDataType(SelectStatement query, out Type dataType, out DbType dbType)
 {
     // Automatically determine data type if possible.
     if (query.SelectList.Count == 1)
     {
         SelectItem firstItem = query.SelectList[0];
         if (firstItem.ItemType == SqlItemType.Column)
         {
             IDbColumn field = (IDbColumn)firstItem.Item;
             dataType = field.DataType;
             dbType = field.DbType;
         }
         else if (firstItem.ItemType == SqlItemType.Function)
         {
             Function function = (Function)firstItem.Item;
             dataType = function.DataType;
             dbType = function.DbType;
         }
         else
         {
             dataType = typeof(object);
             dbType = DbType.Object;
         }
     }
     else
     {
         dataType = typeof(object);
         dbType = DbType.Object;
     }
 }
Пример #23
0
 public static void CreateParameter(this IDbCommand command, string name, DbType dbType)
 {
   IDbDataParameter parameter = command.CreateParameter();
   parameter.ParameterName = name;
   parameter.DbType = dbType;
   command.Parameters.Add(parameter);
 }
Пример #24
0
 /// <summary>
 /// Extension for adding single parameter
 /// </summary>
 public static void AddParam(this DbCommand cmd, object item, DbType? type = null)
 {
     var p = cmd.CreateParameter();
     p.ParameterName = string.Format("@{0}", cmd.Parameters.Count);
     if (item == null)
     {
         p.Value = DBNull.Value;
     }
     else
     {
         if (item.GetType() == typeof(Guid))
         {
             p.Value = item.ToString();
             p.DbType = DbType.String;
             p.Size = 4000;
         }
         else if (item.GetType() == typeof(ExpandoObject))
         {
             var d = (IDictionary<string, object>)item;
             p.Value = d.Values.FirstOrDefault();
         }
         else
         {
             p.Value = item;
             if (type.HasValue)
                 p.DbType = type.Value;
         }
         if (item.GetType() == typeof(string))
             p.Size = ((string)item).Length > 4000 ? -1 : 4000;
     }
     cmd.Parameters.Add(p);
 }
Пример #25
0
 public Column(string name, DbType type)
 {
     ColumnName = name;
     IsAutoIncrement = false;
     Type = type;
     IsNullable = true;
 }
Пример #26
0
 public ExtendedProperty(string name, object value, DbType dataType, PropertyStateEnum state)
 {
     this.name = name;
     this.value = value;
     this.dataType = dataType;
     this.propertyState = state;
 }
        protected override IDataParameter GetParameter(string name, object paramValue, DbType datatype)
        {
            object value = paramValue;
            DbType localDatatype = datatype;
            if (datatype == DbType.Guid)
                localDatatype = DbType.String;
            else
                localDatatype = datatype;

            NpgsqlParameter param;
            if (datatype == DbType.Guid && value != DBNull.Value)
            {
                value = new Guid(paramValue.ToString());
                param = new NpgsqlParameter(name, localDatatype);
                param.Value = value;
            }
            else
            {
                param = new NpgsqlParameter(name, value);
                param.DbType = localDatatype;

            }

            return param;
        }
        public RelationalTypeMapping([NotNull] string defaultTypeName, DbType? storeType = null)
        {
            Check.NotEmpty(defaultTypeName, nameof(defaultTypeName));

            DefaultTypeName = defaultTypeName;
            StoreType = storeType;
        }
Пример #29
0
 public ExtendedProperty(string name, object value, DbType dataType)
 {
     this.name = name;
     this.value = value;
     this.dataType = dataType;
     this.propertyState = PropertyStateEnum.Unmodified;
 }
Пример #30
0
		public DbParameter CreateParameter(Type connectionType, string sourceColumn, ParameterDirection parameterDirection, DbType parameterDbType, int parameterSize, byte parameterPrecision, byte parameterScale, bool parameterNullable, string parameterName, object parameterValue)
		{
			DbParameter dbParameter;

			if ((object)connectionType == null)
				throw new ArgumentNullException(nameof(connectionType));

			using (DbConnection dbConnection = (DbConnection)Activator.CreateInstance(connectionType))
			{
				using (DbCommand dbCommand = dbConnection.CreateCommand())
					dbParameter = dbCommand.CreateParameter();

				dbParameter.ParameterName = parameterName;
				dbParameter.Size = parameterSize;
				dbParameter.Value = parameterValue;
				dbParameter.Direction = parameterDirection;
				dbParameter.DbType = parameterDbType;
				this.ReflectionFascade.SetLogicalPropertyValue(dbParameter, "IsNullable", parameterNullable, true, false);
				dbParameter.Precision = parameterPrecision;
				dbParameter.Scale = parameterScale;
				dbParameter.SourceColumn = sourceColumn;

				return dbParameter;
			}
		}
Пример #31
0
        public static IFullNodeBuilder UsePosConsensus(this IFullNodeBuilder fullNodeBuilder, DbType coindbType = DbType.Rocksdb)
        {
            LoggingConfiguration.RegisterFeatureNamespace <PosConsensusFeature>("posconsensus");

            fullNodeBuilder.ConfigureFeature(features =>
            {
                features
                .AddFeature <PosConsensusFeature>()
                .FeatureServices(services =>
                {
                    AddCoindbImplementation(services, coindbType);
                    services.AddSingleton <IStakdb>(provider => (IStakdb)provider.GetService <ICoindb>());
                    services.AddSingleton <ICoinView, CachedCoinView>();
                    services.AddSingleton <StakeChainStore>().AddSingleton <IStakeChain, StakeChainStore>(provider => provider.GetService <StakeChainStore>());
                    services.AddSingleton <IStakeValidator, StakeValidator>();
                    services.AddSingleton <IRewindDataIndexCache, RewindDataIndexCache>();
                    services.AddSingleton <IConsensusRuleEngine, PosConsensusRuleEngine>();
                    services.AddSingleton <IChainState, ChainState>();
                    services.AddSingleton <ConsensusQuery>()
                    .AddSingleton <INetworkDifficulty, ConsensusQuery>(provider => provider.GetService <ConsensusQuery>())
                    .AddSingleton <IGetUnspentTransaction, ConsensusQuery>(provider => provider.GetService <ConsensusQuery>());
                    services.AddSingleton <IProvenBlockHeaderStore, ProvenBlockHeaderStore>();
                    services.AddSingleton <IProvenBlockHeaderRepository, ProvenBlockHeaderRepository>();
                });
            });

            return(fullNodeBuilder);
        }
Пример #32
0
 public abstract void AddParameter(IDbCommand command, string paramName, DbType type);
Пример #33
0
 public abstract void AddParameterWithValue(IDbCommand command, string paramName, DbType type,
                                            ParameterDirection direction, object value);
Пример #34
0
 public CsqCommonFunction(BQLValueItem[] values, DelCommonFunction funHandle, DbType dbType)
 {
     this.funHandle    = funHandle;
     this.values       = values;
     this._valueDbType = dbType;
 }
 internal static ArgumentException DbTypeNotSupported(DbType type, Type enumtype)
 {
     return(Argument(SR.GetString(SR.ADP_DbTypeNotSupported, type.ToString(), enumtype.Name)));
 }
Пример #36
0
 public static SQLiteParameter AddSqlParm(string ParmName, object Value, DbType Sqltype)
 {
     return(AddSqlParm(ParmName, Value, Sqltype, -1));
 }
Пример #37
0
 IAlteredColumn IExistingColumn.AlterToNotNullable(DbType dbType)
 {
     _command.Add(new AlterColumnDefinitionCommand(_command, dbType, false));
     return(this);
 }
Пример #38
0
        /// <summary>
        /// Look up a DbType from a .Net type.
        /// </summary>
        /// <param name="type">The type of object to look up.</param>
        /// <param name="serializer">The serializer that has been detected for the field.</param>
        /// <param name="parameterType">The expected sql parameter type. Used as the default.</param>
        /// <returns>The equivalent DbType.</returns>
        private static DbType LookupDbType(Type type, IDbObjectSerializer serializer, DbType parameterType)
        {
            DbType sqlType;

            // if the serializer can serialize it, then it's a string
            if (serializer != null && serializer.CanSerialize(type, parameterType))
            {
                return(serializer.GetSerializedDbType(type, parameterType));
            }

            // if the type is nullable, get the underlying type
            var nullUnderlyingType = Nullable.GetUnderlyingType(type);

            if (nullUnderlyingType != null)
            {
                type = nullUnderlyingType;
            }

            // if it's an enum, get the underlying type
            if (type.GetTypeInfo().IsEnum)
            {
                type = Enum.GetUnderlyingType(type);
            }

            // look up the type
            if (_typeToDbTypeMap.TryGetValue(type, out sqlType))
            {
                return(sqlType);
            }

            // special cases for XmlDocument and XDocument
            if (type == typeof(XmlDocument))
            {
                return(DbType.Xml);
            }
            if (type == typeof(XDocument))
            {
                return(DbType.Xml);
            }

            // support for enumerables
            if (typeof(IEnumerable).IsAssignableFrom(type))
            {
                // use -1 to denote its a list, hacky but will work on any DB
                return(DbTypeEnumerable);
            }

            // sql udts are udts
            if (TypeHelper.IsSqlUserDefinedType(type))
            {
                return(DbType.Object);
            }

            // let's see if the type can be directly converted to the parameter type
            return(parameterType);
        }
Пример #39
0
        private static Action <IDbCommand, object> CreateClassInputParameterGenerator(IDbCommand command, Type type)
        {
            var provider   = InsightDbProvider.For(command);
            var parameters = provider.DeriveParameters(command);

            // special case if the parameters object is an IEnumerable or Array
            // look for the parameter that is a Structured object and pass the array to the TVP
            // note that string supports ienumerable, so exclude atomic types
            var enumerable = type.GetInterfaces().FirstOrDefault(i => i.GetTypeInfo().IsGenericType&& i.GetGenericTypeDefinition() == typeof(IEnumerable <>));

            if (enumerable != null && type != typeof(string) && parameters.OfType <IDataParameter>().Where(p => p.Direction.HasFlag(ParameterDirection.Input)).Count() == 1)
            {
                return((IDbCommand cmd, object o) =>
                {
                    // don't use the provider above. The command may be unwrapped by the time we get back here
                    var tableParameter = InsightDbProvider.For(cmd).CloneParameter(cmd, parameters.OfType <IDataParameter>().Single(p => p.Direction.HasFlag(ParameterDirection.Input)));
                    cmd.Parameters.Add(tableParameter);
                    ListParameterHelper.ConvertListParameter(tableParameter, o, cmd);
                });
            }

            // get the mapping of the properties for the type
            var mappings = ColumnMapping.MapParameters(type, command, parameters);

            // start creating a dynamic method
            Type typeOwner = type.HasElementType ? type.GetElementType() : type;
            var  dm        = new DynamicMethod(String.Format(CultureInfo.InvariantCulture, "CreateInputParameters-{0}", Guid.NewGuid()), null, new[] { typeof(IDbCommand), typeof(object) }, typeOwner, true);
            var  il        = dm.GetILGenerator();

            // copy the parameters into the command object
            var parametersLocal = il.DeclareLocal(typeof(IDataParameter[]));

            StaticFieldStorage.EmitLoad(il, provider);
            il.Emit(OpCodes.Ldarg_0);
            StaticFieldStorage.EmitLoad(il, parameters);
            il.Emit(OpCodes.Call, typeof(InsightDbProvider).GetMethod("CopyParameters", BindingFlags.NonPublic | BindingFlags.Instance));
            il.Emit(OpCodes.Stloc, parametersLocal);

            // go through all of the mappings
            for (int i = 0; i < mappings.Count; i++)
            {
                var mapping     = mappings[i];
                var dbParameter = parameters[i];

                // if there is no mapping for the parameter
                if (mapping == null)
                {
                    // sql will silently eat table parameters that are not specified, and that can be difficult to debug
                    if (provider.IsTableValuedParameter(command, dbParameter))
                    {
                        throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Table parameter {0} must be specified", dbParameter.ParameterName));
                    }

                    // unspecified input parameters get skipped
                    if (dbParameter.Direction == ParameterDirection.Input)
                    {
                        parameters[i] = null;
                    }

                    continue;
                }

                var memberType = mapping.Member.MemberType;
                var serializer = mapping.Serializer;

                // get the parameter
                il.Emit(OpCodes.Ldloc, parametersLocal);
                il.Emit(OpCodes.Ldc_I4, i);
                il.Emit(OpCodes.Ldelem, typeof(IDataParameter));

                // look up the best type to use for the parameter
                DbType sqlType = LookupDbType(memberType, serializer, dbParameter.DbType);
                // give the provider an opportunity to fix up the template parameter (e.g. set UDT type names)
                provider.FixupParameter(command, dbParameter, sqlType, memberType, mapping.Member.SerializationMode);
                // give a chance to override the best guess parameter
                DbType overriddenSqlType = ColumnMapping.MapParameterDataType(memberType, command, dbParameter, sqlType);

                ///////////////////////////////////////////////////////////////
                // We have a parameter, start handling all of the other types
                ///////////////////////////////////////////////////////////////
                if (overriddenSqlType != sqlType)
                {
                    sqlType            = overriddenSqlType;
                    dbParameter.DbType = sqlType;
                }

                ///////////////////////////////////////////////////////////////
                // Get the value from the object onto the stack
                ///////////////////////////////////////////////////////////////
                il.Emit(OpCodes.Ldarg_1);
                if (type.GetTypeInfo().IsValueType)
                {
                    il.Emit(OpCodes.Unbox_Any, type);
                }

                ///////////////////////////////////////////////////////////////
                // Special case support for enumerables. If the type is -1 (our workaround, then call the list parameter method)
                ///////////////////////////////////////////////////////////////
                if (sqlType == DbTypeEnumerable)
                {
                    // we have the parameter and the value as object, add the command
                    ClassPropInfo.EmitGetValue(type, mapping.PathToMember, il);
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Call, typeof(ListParameterHelper).GetMethod("ConvertListParameter", BindingFlags.Static | BindingFlags.NonPublic));
                    continue;
                }

                Label readyToSetLabel = il.DefineLabel();
                ClassPropInfo.EmitGetValue(type, mapping.PathToMember, il, readyToSetLabel);

                // special conversions for timespan to datetime
                if ((sqlType == DbType.Time && dbParameter.DbType != DbType.Time) ||
                    (dbParameter.DbType == DbType.DateTime || dbParameter.DbType == DbType.DateTime2 || dbParameter.DbType == DbType.DateTimeOffset))
                {
                    IlHelper.EmitLdInt32(il, (int)dbParameter.DbType);
                    il.Emit(OpCodes.Call, typeof(TypeConverterGenerator).GetMethod("ObjectToSqlDateTime"));
                }

                // if it's class type, boxed value type (in an object), or nullable, then we have to check for null
                if (!memberType.GetTypeInfo().IsValueType || Nullable.GetUnderlyingType(memberType) != null)
                {
                    Label notNull = il.DefineLabel();

                    // check to see if it's not null
                    il.Emit(OpCodes.Dup);
                    il.Emit(OpCodes.Brtrue, notNull);

                    // it's null. replace the value with DbNull
                    il.Emit(OpCodes.Pop);
                    il.Emit(OpCodes.Ldsfld, _dbNullValue);

                    // value is set to null. ready to set the property.
                    il.Emit(OpCodes.Br, readyToSetLabel);

                    // we know the value is not null
                    il.MarkLabel(notNull);
                }

                ///////////////////////////////////////////////////////////////
                // if this is a linq binary, convert it to a byte array
                ///////////////////////////////////////////////////////////////
                if (memberType == TypeHelper.LinqBinaryType)
                {
                    il.Emit(OpCodes.Callvirt, TypeHelper.LinqBinaryToArray);
                }
                else if (memberType == typeof(XmlDocument))
                {
                    // we are sending up an XmlDocument. ToString just returns the classname, so use the outerxml.
                    il.Emit(OpCodes.Callvirt, memberType.GetProperty("OuterXml").GetGetMethod());
                }
                else if (memberType == typeof(XDocument))
                {
                    // we are sending up an XDocument. Use ToString.
                    il.Emit(OpCodes.Callvirt, memberType.GetMethod("ToString", new Type[] { }));
                }
                else if (serializer != null && serializer.CanSerialize(memberType, sqlType))
                {
                    il.EmitLoadType(memberType);
                    StaticFieldStorage.EmitLoad(il, serializer);
                    il.Emit(OpCodes.Call, typeof(DbParameterGenerator).GetMethod("SerializeParameterValue", BindingFlags.NonPublic | BindingFlags.Static));
                }

                ///////////////////////////////////////////////////////////////
                // p.Value = value
                ///////////////////////////////////////////////////////////////
                // push parameter is at top of method
                // value is above
                il.MarkLabel(readyToSetLabel);
                if (memberType == typeof(string))
                {
                    il.Emit(OpCodes.Call, typeof(DbParameterGenerator).GetMethod("SetParameterStringValue", BindingFlags.NonPublic | BindingFlags.Static));
                }
                else if ((memberType == typeof(Guid?) || (memberType == typeof(Guid))) && dbParameter.DbType != DbType.Guid && command.CommandType == CommandType.StoredProcedure)
                {
                    il.Emit(OpCodes.Call, typeof(DbParameterGenerator).GetMethod("SetParameterGuidValue", BindingFlags.NonPublic | BindingFlags.Static));
                }
                else
                {
                    il.Emit(OpCodes.Callvirt, _iDataParameterSetValue);
                }
            }

            il.Emit(OpCodes.Ret);

            return((Action <IDbCommand, object>)dm.CreateDelegate(typeof(Action <IDbCommand, object>)));
        }
Пример #40
0
        public static IFullNodeBuilder UsePowConsensus(this IFullNodeBuilder fullNodeBuilder, DbType coindbType = DbType.Rocksdb)
        {
            LoggingConfiguration.RegisterFeatureNamespace <PowConsensusFeature>("powconsensus");

            fullNodeBuilder.ConfigureFeature(features =>
            {
                features
                .AddFeature <PowConsensusFeature>()
                .FeatureServices(services =>
                {
                    AddCoindbImplementation(services, coindbType);
                    services.AddSingleton <ConsensusOptions, ConsensusOptions>();
                    services.AddSingleton <ICoinView, CachedCoinView>();
                    services.AddSingleton <IConsensusRuleEngine, PowConsensusRuleEngine>();
                    services.AddSingleton <IChainState, ChainState>();
                    services.AddSingleton <ConsensusQuery>()
                    .AddSingleton <INetworkDifficulty, ConsensusQuery>(provider => provider.GetService <ConsensusQuery>())
                    .AddSingleton <IGetUnspentTransaction, ConsensusQuery>(provider => provider.GetService <ConsensusQuery>());
                });
            });

            return(fullNodeBuilder);
        }
Пример #41
0
 protected SqlParameter CreateSqlParameter(string parameterName, object value, DbType dbType, ParameterDirection direction = ParameterDirection.Input)
 {
     return(new SqlParameter(parameterName, value ?? DBNull.Value)
     {
         Direction = direction,
         DbType = dbType
     });
 }
Пример #42
0
        /// <summary>
        /// Create a parameter generator for a dynamic object.
        /// </summary>
        /// <param name="command">The command to parse.</param>
        /// <returns>An action that fills in the command parameters from a dynamic object.</returns>
        private static Action <IDbCommand, object> CreateDynamicInputParameterGenerator(IDbCommand command)
        {
            var provider   = InsightDbProvider.For(command);
            var parameters = provider.DeriveParameters(command);

            return((cmd, o) =>
            {
                // make sure that we have a dictionary implementation
                IDictionary <string, object> dyn = o as IDictionary <string, object>;
                if (dyn == null)
                {
                    throw new InvalidOperationException("Dynamic object must support IDictionary<string, object>.");
                }

                foreach (var template in parameters)
                {
                    var p = provider.CloneParameter(cmd, template);

                    // get the value from the object, converting null to db null
                    // note that if the dictionary does not have the value, we leave the value null and then the parameter gets defaulted
                    object value = null;
                    if (dyn.TryGetValue(p.ParameterName, out value))
                    {
                        if (value == null)
                        {
                            value = DBNull.Value;
                        }
                        else
                        {
                            DbType sqlType = LookupDbType(value.GetType(), null, p.DbType);
                            if (sqlType == DbTypeEnumerable)
                            {
                                cmd.Parameters.Add(p);
                                ListParameterHelper.ConvertListParameter(p, value, cmd);
                                continue;
                            }
                        }
                    }

                    p.Value = value;

                    // if it's a string, fill in the length
                    IDbDataParameter dbDataParameter = p as IDbDataParameter;
                    if (dbDataParameter != null)
                    {
                        string s = value as string;
                        if (s != null)
                        {
                            int length = s.Length;
                            if (length > 4000)
                            {
                                length = -1;
                            }
                            dbDataParameter.Size = length;
                        }
                    }

                    // explicitly set the type of the parameter
                    if (value != null && _typeToDbTypeMap.ContainsKey(value.GetType()))
                    {
                        dbDataParameter.DbType = _typeToDbTypeMap[value.GetType()];
                    }

                    cmd.Parameters.Add(p);
                }
            });
        }
Пример #43
0
 public SqlParameter(string parameterName,
                     DbType dataType,
                     string parameterValue)
     : this(parameterName, dataType, parameterValue, ParameterDirection.Input)
 {
 }
Пример #44
0
 public string CreateSelectSql(DbType dbType, ValueKind kind) => SqlServerDatabase.CreateSelectSql(dbType, kind);
Пример #45
0
 /// <summary>
 /// Get the datastore MaxLength for DbParameter
 /// </summary>
 public abstract Int32 GetMaxLengthFromDbType(DbType dbType, Int32 maxLength);
Пример #46
0
 /// <summary>
 /// 功能描述:设置初始化参数
 /// 作  者:LX_Core
 /// </summary>
 /// <param name="strConnectionString">连接字符串</param>
 /// <param name="enmDbType">数据库类型</param>
 public static void Init(string strConnectionString, DbType enmDbType = SqlSugar.DbType.SqlServer)
 {
     _connectionString = strConnectionString;
     _dbType           = enmDbType;
 }
Пример #47
0
 /// <summary>
 /// Get the datastore precision / scale / length string for generating scripts
 /// </summary>
 public abstract string GetPrecisionStringFromDbType(DbType dbType, int maxLength, byte precision, byte scale);
Пример #48
0
 /// <summary>
 /// Gets the corresponding DbType from a owner dbtype
 /// </summary>
 public abstract object GetOwnerDbTypeFromDbType(DbType dbType);
Пример #49
0
        public (byte precision, byte scale) TryGetOwnerPrecisionAndScale(string originalDbType, DbType fallbackDbType, bool isUnsigned, bool isUnicode, byte precision, byte scale, string fromProviderType, string ownerProviderType)
        {
            // We MUST check if we are from the same provider (if it's mysql or oracle, we fallback on dbtype
            if (!String.IsNullOrEmpty(originalDbType) && fromProviderType == ownerProviderType)
            {
                SqlDbType sqlDbType = (SqlDbType)ValidateOwnerDbType(originalDbType, isUnsigned, isUnicode);
                return(GetPrecisionFromOwnerDbType(sqlDbType, precision, scale));
            }

            // if it's not the same provider, fallback on DbType instead.
            return(GetPrecisionFromDbType(fallbackDbType, precision, scale));
        }
Пример #50
0
 /// <summary>
 /// Get the datastore precision / scale for DbParameter
 /// </summary>
 public abstract (byte precision, byte scale) GetPrecisionFromDbType(DbType dbType, byte precision, byte scale);
Пример #51
0
        /// <summary>
        /// Determine the data type based on the value
        /// </summary>
        private void InferType()
        {
            if (Value == null)
            {
                throw new ArgumentException("No DB2Parameter.Value found");
            }

            if (Value is IConvertible)
            {
                switch (((IConvertible)Value).GetTypeCode())
                {
                case TypeCode.Char:      dbType = DbType.Byte;       db2Type = DB2Type.SmallInt;    db2DataType = DB2Constants.SQL_WCHAR;           break;

                case TypeCode.Boolean:   dbType = DbType.Byte;       db2Type = DB2Type.SmallInt;    db2DataType = DB2Constants.SQL_BIT;             break;

                case TypeCode.SByte:
                case TypeCode.Byte:      dbType = DbType.Byte;       db2Type = DB2Type.SmallInt;    db2DataType = DB2Constants.SQL_UTINYINT;        break;

                case TypeCode.UInt16:
                case TypeCode.Int16:     dbType = DbType.Int16;      db2Type = DB2Type.SmallInt;    db2DataType = DB2Constants.SQL_SMALLINT;        break;

                case TypeCode.UInt32:
                case TypeCode.Int32:     dbType = DbType.Int32;      db2Type = DB2Type.Integer;     db2DataType = DB2Constants.SQL_INTEGER;         break;

                case TypeCode.UInt64:
                case TypeCode.Int64:     dbType = DbType.Int64;      db2Type = DB2Type.BigInt;      db2DataType = DB2Constants.SQL_BIGINT;          break;

                case TypeCode.Single:    dbType = DbType.Single;     db2Type = DB2Type.Float;       db2DataType = DB2Constants.SQL_REAL;            break;

                case TypeCode.Double:    dbType = DbType.Double;     db2Type = DB2Type.Double;      db2DataType = DB2Constants.SQL_DOUBLE;          break;

                case TypeCode.Decimal:   dbType = DbType.Decimal;    db2Type = DB2Type.Decimal;     db2DataType = DB2Constants.SQL_DECIMAL;         break;

                case TypeCode.DateTime:  dbType = DbType.DateTime;   db2Type = DB2Type.Timestamp;   db2DataType = DB2Constants.SQL_TYPE_TIMESTAMP;  break;

                case TypeCode.String:    dbType = DbType.String;     db2Type = DB2Type.VarChar;     db2DataType = DB2Constants.SQL_WCHAR;           break;

                case TypeCode.Object:
                case TypeCode.DBNull:
                case TypeCode.Empty:
                    throw new SystemException("Unknown data type");

                default:
                    throw new SystemException("Value is of unknown data type");
                }
            }
            else if (Value is byte[])
            {
                dbType      = DbType.Binary;
                db2Type     = DB2Type.VarBinary;
                db2DataType = DB2Constants.SQL_VARBINARY;
            }
            else if (Value is TimeSpan)
            {
                dbType      = DbType.Time;
                db2Type     = DB2Type.Time;
                db2DataType = DB2Constants.SQL_TYPE_TIME;
            }
            else
            {
                throw new NotSupportedException("Value is of unsupported data type");
            }
        }
Пример #52
0
 /// <summary>
 /// Get the datastore type name from a DbType for generating scripts
 /// </summary>
 public abstract string GetStringFromDbType(DbType dbType);
        public static IDbDataParameter CreateParameter(string providerName, string parameterName, object value, DbType dbType, int size = 0, ParameterDirection direction = ParameterDirection.Input)
        {
            IDbDataParameter parameter = null;

            switch (providerName)
            {
            case "System.Data.SqlClient":
                parameter = CreateSqlParameter(parameterName, value, dbType, size, direction);
                break;

            case "System.Data.OdbcClient":
                parameter = CreateOdbcParameter(parameterName, value, dbType, size, direction);
                break;

            default:
                break;
            }

            return(parameter);
        }
Пример #54
0
        /// <inheritdoc/>
        public override void FixupParameter(IDbCommand command, IDataParameter parameter, DbType dbType, Type type, SerializationMode serializationMode)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }
            if (parameter == null)
            {
                throw new ArgumentNullException("parameter");
            }

            base.FixupParameter(command, parameter, dbType, type, serializationMode);

            // when calling sql text, we have to fill in the udttypename for some parameters
            if (command.CommandType != CommandType.StoredProcedure && IsSqlUserDefinedType(type))
            {
                SqlParameter p = (SqlParameter)parameter;
                p.SqlDbType = SqlDbType.Udt;

#if !NO_SQL_TYPES
                switch (type.Name)
                {
                case "SqlGeometry":
                    p.UdtTypeName = "sys.geometry";
                    break;

                case "SqlGeography":
                    p.UdtTypeName = "sys.geography";
                    break;

                case "SqlHierarchy":
                    p.UdtTypeName = "sys.hierarchyid";
                    break;
                }
#endif
            }

            // older versions of SQL Server (CE and 2005) don't support DateTime2
            // newer versions do, so if we have a new version and it's a datetime, make it bigger
            if (parameter.DbType == DbType.DateTime)
            {
                var sc      = (SqlConnection)command.Connection;
                var version = Int32.Parse(sc.ServerVersion.Split('.')[0], CultureInfo.InvariantCulture);
                if (version >= 10)
                {
                    parameter.DbType = DbType.DateTime2;
                }
            }
        }
Пример #55
0
 /// <summary>
 /// 把数据类型转换成当前数据库支持的类型
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public DbType ToCurrentDbType(DbType type)
 {
     return(CurrentDbType(type));
 }
Пример #56
0
        /// <summary>
        /// 把 DbType的类型值 转换为 MySql 数据库中兼容的数据类型
        /// MySql数据精度 http://qimo601.iteye.com/blog/1622368
        /// </summary>
        /// <param name="fieldType">字段的DbType类型值</param>
        /// <param name="length">数据类型的长度</param>
        /// <returns>返回MySql数据库中的具体类型值</returns>
        public override string ConvertToDatabaseTypeName(DbType fieldType, string length = null)
        {
            switch (fieldType)
            {
            case DbType.String:
            case DbType.AnsiString:
                if (!string.IsNullOrEmpty(length) && !string.Equals("max", length, StringComparison.CurrentCultureIgnoreCase))
                {
                    return("VARCHAR(" + length + ")");
                }
                return("TEXT");

            case DbType.Xml:
                return("TEXT");

            case DbType.SByte:
            case DbType.Byte:
                return("TINYINT");

            case DbType.UInt16:
            case DbType.Int16:
                return("SMALLINT");

            case DbType.UInt32:
            case DbType.Int32:
                return("INT");

            case DbType.UInt64:
            case DbType.Int64:
                return("BIGINT");

            case DbType.Time:
                return("TIME");

            case DbType.Date:
                return("DATE");

            case DbType.DateTime:
            case DbType.DateTimeOffset:
                return("DATETIME");

            case DbType.Single:
                return("FLOAT");

            case DbType.Double:
                return("DOUBLE");

            case DbType.Decimal:
                if (!string.IsNullOrWhiteSpace(length))
                {
                    return("DECIMAL(" + length + ")");
                }
                return("DECIMAL(18,2)");

            case DbType.Binary:
                return("BLOB");

            case DbType.Boolean:
                return("TINYINT(1)");

            //return "BIT";// Boolean 映射为 BIT 时,批量导入会出错。
            default:
                break;
            }
            throw new NotSupportedException(string.Format("不支持生成列类型:{0}。", fieldType));
        }
Пример #57
0
        /// <summary>
        /// 把DBType类型转成对应的SQLType
        /// </summary>
        /// <param name="dbType"></param>
        /// <returns></returns>
        public virtual string DBTypeToSQL(DbType dbType, long length)
        {
            int    type  = ToRealDbType(dbType, length);
            DbType stype = (DbType)type;

            switch (stype)
            {
            case DbType.AnsiString:
            case DbType.AnsiStringFixedLength:
            case DbType.String:
            case DbType.StringFixedLength:
                if (length <= 255)
                {
                    return("Text(" + length + ")");
                }
                return("Memo");

            case DbType.Boolean:
                return("YesNo");

            case DbType.Byte:
                return("Byte");

            case DbType.Currency:
                return("Currency");

            case DbType.Date:
                return("Date");

            case DbType.DateTime:
            case DbType.DateTime2:
            case DbType.DateTimeOffset:
            case DbType.Time:
                return("DateTime");

            case DbType.Single:
                return("Single");


            case DbType.Double:
                return("Double");

            case DbType.SByte:
            case DbType.Int16:
                return("Integer");

            case DbType.UInt16:
            case DbType.Int32:
                return("Long");

            case DbType.Int64:
            case DbType.UInt32:
            case DbType.UInt64:
            case DbType.Decimal:
            case DbType.VarNumeric:
                return("Decimal");

            case DbType.Binary:
                return("OLEObject");

            case DbType.Guid:
                return("ReplicationID");

            default:
                return(stype.ToString());
            }
        }
Пример #58
0
 /// <summary>
 /// 获取当前时间
 /// </summary>
 /// <returns></returns>
 public string GetNowDate(DbType dbType)
 {
     return("now()");
 }
Пример #59
0
 public MyField(string fieldName, object fieldValue, Type type)
 {
     this._fieldName  = fieldName;
     this._fieldValue = fieldValue;
     this._dataType   = TableManager.TypeToDbType(type);
 }
Пример #60
0
        /// <summary>
        /// 把DBType转成本数据库的实际类型
        /// </summary>
        /// <param name="dbType"></param>
        /// <returns></returns>
        public virtual int ToRealDbType(DbType dbType, long length)
        {
            //switch (dbType)
            //{
            //    case DbType.AnsiString:
            //        if (length < 8000)
            //        {
            //            return (int)OleDbType.Char;
            //        }
            //        else
            //        {
            //            return (int)OleDbType.LongVarChar;
            //        }
            //    case DbType.AnsiStringFixedLength:
            //        if (length < 8000)
            //        {
            //            return (int)OleDbType.Char;
            //        }
            //        else
            //        {
            //            return (int)OleDbType.LongVarChar;
            //        }
            //    case DbType.Binary:
            //        if (length < 8000)
            //        {
            //            return (int)OleDbType.Binary;
            //        }
            //        else
            //        {
            //            return (int)OleDbType.LongVarBinary;
            //        }
            //    case DbType.Boolean:
            //        return (int)OleDbType.Boolean;
            //    case DbType.Byte:
            //        return (int)OleDbType.UnsignedTinyInt;
            //    case DbType.Currency:
            //        return (int)OleDbType.Currency;
            //    case DbType.Date:
            //        return (int)OleDbType.DBDate;
            //    case DbType.DateTime:
            //    case DbType.DateTime2:
            //    case DbType.DateTimeOffset:
            //        return (int)OleDbType.DBTimeStamp;
            //    case DbType.Time:
            //        return (int)OleDbType.DBTime;
            //    case DbType.Decimal:
            //        return (int)OleDbType.Decimal;
            //    case DbType.Double:
            //        return (int)OleDbType.Double;
            //    case DbType.Guid:
            //        return (int)OleDbType.Guid;
            //    case DbType.Int16:
            //        return (int)OleDbType.SmallInt;
            //    case DbType.UInt16:
            //        return (int)OleDbType.UnsignedSmallInt;
            //    case DbType.Int32:
            //        return (int)OleDbType.Integer;
            //    case DbType.Int64:
            //        return (int)OleDbType.BigInt;
            //    case DbType.SByte:
            //        return (int)OleDbType.TinyInt;
            //    case DbType.Single:
            //        return (int)OleDbType.Single;
            //    case DbType.String:
            //        if (length < 4000)
            //        {
            //            return (int)OleDbType.VarWChar;
            //        }
            //        else
            //        {
            //            return (int)OleDbType.LongVarWChar;
            //        }
            //    case DbType.StringFixedLength:
            //        if (length < 4000)
            //        {
            //            return (int)OleDbType.WChar;
            //        }
            //        else
            //        {
            //            return (int)OleDbType.LongVarWChar;
            //        }

            //    case DbType.UInt32:
            //        return (int)OleDbType.UnsignedInt;
            //    case DbType.UInt64:
            //        return (int)OleDbType.UnsignedBigInt;
            //    case DbType.VarNumeric:
            //        return (int)OleDbType.VarNumeric;
            //    default:
            //        return (int)OleDbType.PropVariant;

            //}
            return((int)dbType);
        }