using System;
using System.Data;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Npgsql.TypeMapping;
using NpgsqlTypes;
namespace Npgsql
{
///
/// A generic version of which provides more type safety and
/// avoids boxing of value types. Use instead of .
///
/// The type of the value that will be stored in the parameter.
public sealed class NpgsqlParameter : NpgsqlParameter
{
///
/// Gets or sets the strongly-typed value of the parameter.
///
[MaybeNull, AllowNull]
public T TypedValue { get; set; } = default!;
///
/// Gets or sets the value of the parameter. This delegates to .
///
#nullable disable
public override object Value
#nullable restore
{
get => TypedValue;
set => TypedValue = (T)value;
}
#region Constructors
///
/// Initializes a new instance of .
///
public NpgsqlParameter() {}
///
/// Initializes a new instance of with a parameter name and value.
///
public NpgsqlParameter(string parameterName, T value)
{
ParameterName = parameterName;
TypedValue = value;
}
///
/// Initializes a new instance of with a parameter name and type.
///
public NpgsqlParameter(string parameterName, NpgsqlDbType npgsqlDbType)
{
ParameterName = parameterName;
NpgsqlDbType = npgsqlDbType;
}
///
/// Initializes a new instance of with a parameter name and type.
///
public NpgsqlParameter(string parameterName, DbType dbType)
{
ParameterName = parameterName;
DbType = dbType;
}
#endregion Constructors
internal override void ResolveHandler(ConnectorTypeMapper typeMapper)
{
if (Handler != null)
return;
// TODO: Better exceptions in case of cast failure etc.
if (_npgsqlDbType.HasValue)
Handler = typeMapper.GetByNpgsqlDbType(_npgsqlDbType.Value);
else if (_dataTypeName != null)
Handler = typeMapper.GetByDataTypeName(_dataTypeName);
else
Handler = typeMapper.GetByClrType(typeof(T));
}
internal override int ValidateAndGetLength()
{
if (TypedValue == null)
return 0;
// TODO: Why do it like this rather than a handler?
if (typeof(T) == typeof(DBNull))
return 0;
var lengthCache = LengthCache;
var len = Handler!.ValidateAndGetLength(TypedValue, ref lengthCache, this);
LengthCache = lengthCache;
return len;
}
internal override Task WriteWithLength(NpgsqlWriteBuffer buf, bool async)
=> Handler!.WriteWithLengthInternal(TypedValue, buf, LengthCache, this, async);
}
}