void DoWrite <T>([CanBeNull] T value, NpgsqlDbType?npgsqlDbType) { CheckReady(); if (_column == -1) { throw new InvalidOperationException("A row hasn't been started"); } if (value == null || value is DBNull) { WriteNull(); return; } var untypedParam = _params[_column]; if (untypedParam == null) { // First row, create the parameter objects _params[_column] = untypedParam = typeof(T) == typeof(object) ? new NpgsqlParameter() : new NpgsqlParameter <T>(); if (npgsqlDbType.HasValue) { untypedParam.NpgsqlDbType = npgsqlDbType.Value; } } if (npgsqlDbType.HasValue && npgsqlDbType.Value != untypedParam.NpgsqlDbType) { throw new InvalidOperationException($"Can't change NpgsqlDbType from {untypedParam.NpgsqlDbType} to {npgsqlDbType.Value}"); } if (typeof(T) == typeof(object)) { untypedParam.Value = value; untypedParam.ResolveHandler(_connector.TypeMapper); untypedParam.ValidateAndGetLength(); untypedParam.LengthCache?.Rewind(); untypedParam.WriteWithLength(_buf, false); untypedParam.LengthCache?.Clear(); } else { var param = untypedParam as NpgsqlParameter <T>; if (param == null) { _params[_column] = param = new NpgsqlParameter <T>(); param.NpgsqlDbType = untypedParam.NpgsqlDbType; } param.TypedValue = value; param.ResolveHandler(_connector.TypeMapper); param.ValidateAndGetLength(); param.LengthCache?.Rewind(); param.WriteWithLength(_buf, false); param.LengthCache?.Clear(); } _column++; }
/// <summary> /// Creates a new instance of <see cref="NpgsqlBulkInsertMapItem"/> object. /// </summary> /// <param name="sourceColumn">The name of the source column or property. This respects the mapping of the properties if the source type is an entity model.</param> /// <param name="destinationColumn">The name of the destination column in the database.</param> /// <param name="npgsqlDbType">The <see cref="NpgsqlTypes.NpgsqlDbType"/> value to be used when writing.</param> public NpgsqlBulkInsertMapItem(string sourceColumn, string destinationColumn, NpgsqlDbType?npgsqlDbType) : base(sourceColumn, destinationColumn) { NpgsqlDbType = npgsqlDbType; }
/// <summary> /// /// </summary> /// <param name="importer"></param> /// <param name="data"></param> /// <param name="npgsqlDbType"></param> private static void BinaryImportWrite(NpgsqlBinaryImporter importer, object data, NpgsqlDbType?npgsqlDbType) { if (data == null) { importer.WriteNull(); } else { if (npgsqlDbType != null) { if (data is Enum) { if (npgsqlDbType == NpgsqlDbType.Integer || npgsqlDbType == NpgsqlDbType.Bigint || npgsqlDbType == NpgsqlDbType.Smallint) { data = Convert.ToInt32(data); } else if (npgsqlDbType == NpgsqlDbType.Text) { data = Convert.ToString(data); } } importer.Write(data, npgsqlDbType.Value); } else { importer.Write(data); } } }
/// <summary> /// 增加一个查询参数 /// </summary> /// <param name="field">数据库字段</param> /// <param name="dbType">字段类型</param> /// <param name="value">字段指定的值</param> /// <param name="size">字段长度</param> /// <returns></returns> public QueryContext <T> AddParameter(string field, NpgsqlDbType?dbType, object value, int size) { NpgsqlParameter p = this.ParamList.FirstOrDefault(f => f.ParameterName == field); if (p != null) { this.ParamList.Remove(p); } if ((dbType == NpgsqlDbType.Json || dbType == NpgsqlDbType.Jsonb) && value != null) { JToken token = value as JToken; if (!token.HasValues) { value = null; } } if (dbType.HasValue) { p = new NpgsqlParameter(field, dbType); } else { p = new NpgsqlParameter(field, value); } if (size != -1) { p.Size = size; } p.Value = value; ParamList.Add(p); return(this); }
/// <summary> /// Reset DBType. /// </summary> public override void ResetDbType() { //type_info = NpgsqlTypesHelper.GetNativeTypeInfo(typeof(String)); _dbType = null; _npgsqlDbType = null; Value = Value; ClearBind(); }
public DocumentMappingExpression <T> Duplicate(Expression <Func <T, object> > expression, string?pgType = null, NpgsqlDbType?dbType = null, Action <DocumentIndex>?configure = null, bool notNull = false) { _builder.Alter = mapping => { mapping.Duplicate(expression, pgType, dbType, configure, notNull); }; return(this); }
/// <summary> /// 转换数据库类型描述为 NpgsqlDbType 类型对象 /// </summary> /// <param name="data_type"></param> /// <param name="db_type"></param> /// <returns></returns> public static NpgsqlDbType?SwitchToSql(string data_type, string db_type) { NpgsqlDbType?_dbtype = null; if (data_type == "e") { _dbtype = null; } else if (db_type == "int2" || db_type == "int4") { _dbtype = NpgsqlDbType.Integer; } else if (db_type == "int8") { _dbtype = NpgsqlDbType.Bigint; } else if (db_type == "bool") { _dbtype = NpgsqlDbType.Boolean; } else if (db_type == "bpchar") { _dbtype = NpgsqlDbType.Char; } else if (db_type == "float4" || db_type == "float8") { _dbtype = NpgsqlDbType.Double; } else if (db_type == "path" || db_type == "line" || db_type == "polygon" || db_type == "circle" || db_type == "point" || db_type == "box" || db_type == "lseg") { if (db_type == "lseg") { db_type = "LSeg"; } } else if (db_type == "interval") { _dbtype = NpgsqlDbType.Interval; } else if (db_type == "macaddr") { _dbtype = NpgsqlDbType.MacAddr; } else { NpgsqlDbType type = NpgsqlDbType.Unknown; if (System.Enum.TryParse <NpgsqlDbType>(db_type.ToUpperPascal(), out type)) { return(type); } } return(_dbtype); }
internal NpgsqlTypeMapping( string pgTypeName, NpgsqlDbType?npgsqlDbType, DbType[] dbTypes, Type[] clrTypes, DbType?inferredDbType, NpgsqlTypeHandlerFactory typeHandlerFactory) { PgTypeName = pgTypeName; NpgsqlDbType = npgsqlDbType; DbTypes = dbTypes ?? EmptyDbTypes; ClrTypes = clrTypes ?? EmptyClrTypes; InferredDbType = inferredDbType; TypeHandlerFactory = typeHandlerFactory; }
/// <summary> /// Maps an Npgsql type handler to a PostgreSQL type. /// </summary> /// <param name="pgName">A PostgreSQL type name as it appears in the pg_type table.</param> /// <param name="npgsqlDbType"> /// A member of <see cref="NpgsqlDbType"/> which represents this PostgreSQL type. /// An <see cref="NpgsqlParameter"/> with <see cref="NpgsqlParameter.NpgsqlDbType"/> set to /// this value will be sent with the type handler mapped by this attribute. /// </param> /// <param name="dbTypes"> /// All members of <see cref="DbType"/> which represent this PostgreSQL type. /// An <see cref="NpgsqlParameter"/> with <see cref="NpgsqlParameter.DbType"/> set to /// one of these values will be sent with the type handler mapped by this attribute. /// </param> /// <param name="clrTypes"> /// Any .NET type which corresponds to this PostgreSQL type. /// An <see cref="NpgsqlParameter"/> with <see cref="NpgsqlParameter.Value"/> set to /// one of these values will be sent with the type handler mapped by this attribute. /// </param> /// <param name="inferredDbType"> /// The "primary" <see cref="DbType"/> which best corresponds to this PostgreSQL type. /// When <see cref="NpgsqlParameter.NpgsqlDbType"/> or <see cref="NpgsqlParameter.Value"/> /// set, <see cref="NpgsqlParameter.DbType"/> will be set to this value. /// </param> internal TypeMappingAttribute(string pgName, NpgsqlDbType?npgsqlDbType, DbType[]?dbTypes, Type[]?clrTypes, DbType?inferredDbType) { if (string.IsNullOrWhiteSpace(pgName)) { throw new ArgumentException("pgName can't be empty", nameof(pgName)); } PgName = pgName; NpgsqlDbType = npgsqlDbType; DbTypes = dbTypes ?? new DbType[0]; ClrTypes = clrTypes ?? new Type[0]; InferredDbType = inferredDbType; }
internal TypeMappingAttribute(string pgName, NpgsqlDbType?npgsqlDbType, DbType[] dbTypes, Type[] types) { if (String.IsNullOrWhiteSpace(pgName)) { throw new ArgumentException("pgName can't be empty", "pgName"); } Contract.EndContractBlock(); PgName = pgName; NpgsqlDbType = npgsqlDbType; DbTypes = dbTypes ?? new DbType[0]; Types = types ?? new Type[0]; }
void BindType(NpgsqlTypeHandler handler, PostgresType pgType, NpgsqlDbType?npgsqlDbType = null, DbType[] dbTypes = null, Type[] clrTypes = null) { _byOID[pgType.OID] = handler; _byTypeName[pgType.FullName] = handler; _byTypeName[pgType.Name] = handler; if (npgsqlDbType.HasValue) { var value = npgsqlDbType.Value; if (_byNpgsqlDbType.ContainsKey(value)) { throw new InvalidOperationException($"Two type handlers registered on same NpgsqlDbType '{npgsqlDbType}': {_byNpgsqlDbType[value].GetType().Name} and {handler.GetType().Name}"); } _byNpgsqlDbType[npgsqlDbType.Value] = handler; } if (dbTypes != null) { foreach (var dbType in dbTypes) { if (_byDbType.ContainsKey(dbType)) { throw new InvalidOperationException($"Two type handlers registered on same DbType {dbType}: {_byDbType[dbType].GetType().Name} and {handler.GetType().Name}"); } _byDbType[dbType] = handler; } } if (clrTypes != null) { foreach (var type in clrTypes) { if (_byClrType.ContainsKey(type)) { throw new InvalidOperationException($"Two type handlers registered on same .NET type '{type}': {_byClrType[type].GetType().Name} and {handler.GetType().Name}"); } _byClrType[type] = handler; } } if (pgType.Array != null) { BindArrayType(handler, pgType.Array, npgsqlDbType, clrTypes); } if (pgType.Range != null) { BindRangeType(handler, pgType.Range, npgsqlDbType, clrTypes); } }
/// <summary> /// Maps an Npgsql type handler to a PostgreSQL type. /// </summary> /// <param name="pgName">A PostgreSQL type name as it appears in the pg_type table.</param> /// <param name="npgsqlDbType"> /// A member of <see cref="NpgsqlDbType"/> which represents this PostgreSQL type. /// An <see cref="NpgsqlParameter"/> with <see cref="NpgsqlParameter.NpgsqlDbType"/> set to /// this value will be sent with the type handler mapped by this attribute. /// </param> /// <param name="dbTypes"> /// All members of <see cref="DbType"/> which represent this PostgreSQL type. /// An <see cref="NpgsqlParameter"/> with <see cref="NpgsqlParameter.DbType"/> set to /// one of these values will be sent with the type handler mapped by this attribute. /// </param> /// <param name="clrTypes"> /// Any .NET type which corresponds to this PostgreSQL type. /// An <see cref="NpgsqlParameter"/> with <see cref="NpgsqlParameter.Value"/> set to /// one of these values will be sent with the type handler mapped by this attribute. /// </param> /// <param name="inferredDbType"> /// The "primary" <see cref="DbType"/> which best corresponds to this PostgreSQL type. /// When <see cref="NpgsqlParameter.NpgsqlDbType"/> or <see cref="NpgsqlParameter.Value"/> /// set, <see cref="NpgsqlParameter.DbType"/> will be set to this value. /// </param> internal TypeMappingAttribute(string pgName, NpgsqlDbType?npgsqlDbType, [CanBeNull] DbType[] dbTypes, [CanBeNull] Type[] clrTypes, DbType?inferredDbType) { if (String.IsNullOrWhiteSpace(pgName)) { throw new ArgumentException("pgName can't be empty", nameof(pgName)); } Contract.EndContractBlock(); PgName = pgName; NpgsqlDbType = npgsqlDbType; DbTypes = dbTypes ?? new DbType[0]; ClrTypes = clrTypes ?? new Type[0]; InferredDbType = inferredDbType; }
protected NpgsqlArrayTypeMapping( RelationalTypeMappingParameters parameters, [NotNull] RelationalTypeMapping elementMapping) : base(parameters) { ElementMapping = elementMapping; // If the element mapping has an NpgsqlDbType or DbType, set our own NpgsqlDbType as an array of that. // Otherwise let the ADO.NET layer infer the PostgreSQL type. We can't always let it infer, otherwise // when given a byte[] it will infer byte (but we want smallint[]) NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Array | (elementMapping is NpgsqlTypeMapping elementNpgsqlTypeMapping ? elementNpgsqlTypeMapping.NpgsqlDbType : elementMapping.DbType.HasValue ? new NpgsqlParameter { DbType = elementMapping.DbType.Value }.NpgsqlDbType : default(NpgsqlDbType?)); }
/// <summary> /// /// </summary> /// <param name="importer"></param> /// <param name="data"></param> /// <param name="npgsqlDbType"></param> /// <param name="cancellationToken"></param> /// <returns></returns> private static async Task BinaryImportWriteAsync(NpgsqlBinaryImporter importer, object data, NpgsqlDbType?npgsqlDbType, CancellationToken cancellationToken = default) { if (data == null) { await importer.WriteNullAsync(cancellationToken); } else { if (npgsqlDbType != null) { await importer.WriteAsync(data, npgsqlDbType.Value, cancellationToken); } else { await importer.WriteAsync(data, cancellationToken); } } }
void BindArrayType(NpgsqlTypeHandler elementHandler, PostgresArrayType pgArrayType, NpgsqlDbType?elementNpgsqlDbType, Type[] elementClrTypes) { var arrayHandler = elementHandler.CreateArrayHandler(pgArrayType); var arrayNpgsqlDbType = elementNpgsqlDbType.HasValue ? NpgsqlDbType.Array | elementNpgsqlDbType.Value : (NpgsqlDbType?)null; BindType(arrayHandler, pgArrayType, arrayNpgsqlDbType); // Note that array handlers aren't registered in ByClrType like base types, because they handle all // dimension types and not just one CLR type (e.g. int[], int[,], int[,,]). // So the by-type lookup is special and goes via _arrayHandlerByClrType, see this[Type type] // TODO: register single-dimensional in _byType as a specific optimization? But do PSV as well... if (elementClrTypes != null) { foreach (var elementType in elementClrTypes) { if (_arrayHandlerByClrType.ContainsKey(elementType)) { throw new Exception( $"Two array type handlers registered on same .NET type {elementType}: {_arrayHandlerByClrType[elementType].GetType().Name} and {arrayHandler.GetType().Name}"); } _arrayHandlerByClrType[elementType] = arrayHandler; } } }
public DocumentMappingExpression <T> Searchable(Expression <Func <T, object> > expression, string?pgType = null, NpgsqlDbType?dbType = null, Action <DocumentIndex>?configure = null) { return(Duplicate(expression, pgType, dbType, configure)); }
/// <summary> /// 实例化 <see cref="_SqlDbType"/> 类的新实例 /// </summary> /// <param name="dbType">.NET 自带DbType</param> /// <param name="sqlDbType">其它数据库组件的DbType</param> NpgDbTypeInfo(DbType?dbType = null, NpgsqlDbType?sqlDbType = null) { this.DbType = dbType; this.SqlDbType = sqlDbType; }
/// <summary> /// Marks a property or field on this document type as a searchable field that is also duplicated in the /// database document table /// </summary> /// <param name="expression"></param> /// <param name="pgType">Optional, overrides the Postgresql column type for the duplicated field</param> /// <param name="configure"> /// Optional, allows you to customize the Postgresql database index configured for the duplicated /// field /// </param> /// <returns></returns> public void Duplicate(Expression <Func <T, object> > expression, string pgType = null, NpgsqlDbType?dbType = null, Action <DocumentIndex> configure = null, bool notNull = false) { var visitor = new FindMembers(); visitor.Visit(expression); var duplicateField = DuplicateField(visitor.Members.ToArray(), pgType, notNull: notNull); if (dbType.HasValue) { duplicateField.DbType = dbType.Value; } var indexDefinition = AddIndex(duplicateField.ColumnName); configure?.Invoke(indexDefinition); }
protected TypeHandlerTestBase(MultiplexingMode multiplexingMode, NpgsqlDbType?npgsqlDbType, string?typeName, string?minVersion = null) : base(multiplexingMode) => (_npgsqlDbType, _typeName, _minVersion) = (npgsqlDbType, typeName, minVersion);
/// <summary> /// Пишет значение в импортер /// </summary> protected virtual void WriteValue(NpgsqlBinaryImporter writer, object value, bool valueSpecified, NpgsqlDbType?type = null) { if (!valueSpecified || value == null || value == DBNull.Value) { writer.WriteNull(); } else if (type.HasValue) { writer.Write(value, type.Value); } else { writer.Write(value); } //Запись о том что столбец передан writer.Write(valueSpecified); }
public static NpgsqlParameter AddParameter(this NpgsqlCommand command, object value, NpgsqlDbType?dbType = null) { var name = "arg" + command.Parameters.Count; var parameter = command.CreateParameter(); parameter.ParameterName = name; parameter.Value = value ?? DBNull.Value; if (dbType.HasValue) { parameter.NpgsqlDbType = dbType.Value; } command.Parameters.Add(parameter); return(parameter); }
public static void RegisterMapping(Type type, string pgType, NpgsqlDbType?npgsqlDbType) { PgTypeMemo.Swap(d => d.AddOrUpdate(type, pgType)); NpgsqlDbTypeMemo.Swap(d => d.AddOrUpdate(type, npgsqlDbType)); }
protected TypeHandlerTestBase(MultiplexingMode multiplexingMode, NpgsqlDbType?npgsqlDbType, string?typeName) : base(multiplexingMode) => (_npgsqlDbType, _typeName) = (npgsqlDbType, typeName);
void BindRangeType(NpgsqlTypeHandler elementHandler, PostgresRangeType pgRangeType, NpgsqlDbType?elementNpgsqlDbType, Type[]?elementClrTypes) { var rangeHandler = elementHandler.CreateRangeHandler(pgRangeType); var rangeNpgsqlDbType = elementNpgsqlDbType.HasValue ? NpgsqlDbType.Range | elementNpgsqlDbType.Value : (NpgsqlDbType?)null; // We only want to bind supported range CLR types whose element CLR types are being bound as well. var clrTypes = elementClrTypes is null ? null : rangeHandler.SupportedRangeClrTypes .Where(r => elementClrTypes.Contains(r.GenericTypeArguments[0])) .ToArray(); BindType((NpgsqlTypeHandler)rangeHandler, pgRangeType, rangeNpgsqlDbType, null, clrTypes); }
public TypeMappingInfo(NpgsqlDbType?npgsqlDbType, string?dataTypeName, Type clrType) => (NpgsqlDbType, DataTypeName, ClrTypes) = (npgsqlDbType, dataTypeName, new[] { clrType });
void BindRangeType(NpgsqlTypeHandler elementHandler, PostgresRangeType pgRangeType, NpgsqlDbType?elementNpgsqlDbType, Type[] elementClrTypes) { var rangeHandler = elementHandler.CreateRangeHandler(pgRangeType); var rangeNpgsqlDbType = elementNpgsqlDbType.HasValue ? NpgsqlDbType.Range | elementNpgsqlDbType.Value : (NpgsqlDbType?)null; Type[] clrTypes = null; if (elementClrTypes != null) { // Somewhat hacky. Although the element may have more than one CLR mapping, // its range will only be mapped to the "main" one for now. var defaultElementType = elementHandler.GetFieldType(); clrTypes = elementClrTypes.Contains(defaultElementType) ? new[] { rangeHandler.GetFieldType() } : null; } BindType(rangeHandler, pgRangeType, rangeNpgsqlDbType, null, clrTypes); }
public NpgsqlParameterCell(Cell cell, string parameterName, ParameterDirection direction, NpgsqlDbType?dbType = null) : base(cell, parameterName, direction) { NpgsqlDbType = dbType; }
/// <summary>Gets the parameter.</summary> /// <param name="parameter">The parameter.</param> /// <param name="value">The value.</param> /// <param name="sqlType">Type of the SQL.</param> /// <returns>NpgsqlParameter.</returns> protected static NpgsqlParameter GetParameter(string parameter, object value, NpgsqlDbType?sqlType = null) { NpgsqlParameter parameterObject; if (value != null) { var type = value.GetType(); if (type.IsEnum) { parameterObject = new NpgsqlParameter(parameter, (int)value); } else if (sqlType is NpgsqlDbType.Json && type != typeof(string)) { parameterObject = new NpgsqlParameter(parameter, JsonConvert.SerializeObject(value)); } else { parameterObject = new NpgsqlParameter(parameter, value); } } else { parameterObject = new NpgsqlParameter(parameter, DBNull.Value); } parameterObject.Direction = ParameterDirection.Input; if (sqlType != null) { parameterObject.NpgsqlDbType = (NpgsqlDbType)sqlType; } return(parameterObject); }
public NpgsqlParameter AddParameter(object value, NpgsqlDbType?dbType = null) { return(_command.AddParameter(value, dbType)); }
/// <summary> /// Marks a property or field on this document type as a searchable field that is also duplicated in the /// database document table /// </summary> /// <param name="expression"></param> /// <param name="pgType">Optional, overrides the Postgresql column type for the duplicated field</param> /// <param name="configure">Optional, allows you to customize the Postgresql database index configured for the duplicated field</param> /// <param name="dbType">Optional, overrides the Npgsql DbType for any parameter usage of this property</param> /// <returns></returns> public DocumentMappingExpression <T> Duplicate(Expression <Func <T, object> > expression, string pgType = null, NpgsqlDbType?dbType = null, Action <IndexDefinition> configure = null) { alter = mapping => { mapping.Duplicate(expression, pgType, dbType, configure); }; return(this); }