Skip to content

Feature Request: Customize Mapping Handlers for Base types #1765

Closed

Description

@speige

When calling any of the NpgsqlCommand.Execute* methods, I'd like to make the default mapping from system.string point to citext instead of text.

The only way I know how to do this is via:

class CitextParameter : SqlMapper.ICustomQueryParameter
{
    readonly string _value;

    public CitextParameter(string value)
    {
        _value = value;
    }

    public void AddParameter(IDbCommand command, string name)
    {
        command.Parameters.Add(new NpgsqlParameter
        {
            ParameterName = name,
            NpgsqlDbType = NpgsqlDbType.Citext,
            Value = _value
        });
    }
}

This would be fine if I was using NpgsqlCommand, because I would be manually creating each param anyway. However, I'm using Dapper, which allows me to pass an object & have it auto-mapped to parameters.

Dapper uses the built-in SqlDbType & npgsql translates them to NpgsqlDbType during execution. So, I don't think this can be fixed by a change in Dapper.

I could modify the SqlDbType =>NpgsqlDbType mappping in npgsql by creating a custom Handler with TypeMapping attributes, however, these classes are all internal.

Example:

//text & citext reversed compared to Npgsql.TextHandler
[TypeMapping("text", NpgsqlDbType.Text, DbType.String)]
[TypeMapping("citext", NpgsqlDbType.Citext, new DbType[] { DbType.String, DbType.StringFixedLength, DbType.AnsiString, DbType.AnsiStringFixedLength }, new Type[] { typeof(string), typeof(char[]), typeof(char), typeof(ArraySegment<char>) }, DbType.String)]
public class CustomTextHandler : Npgsql.TextHandler
{
	
}

Without this, I need to type-cast every text variable in every SQL statement or manually map every parameter to CitextParameter.

Is there a global way to do this that I'm overlooking?

P.S. This is an awesome library. Thank you!

Activity

  1. speige commented on Jan 2, 2018

    @speige
    Author

    I have found a workaround via reflection, but it's not pretty. It essentially lets the static constructor of TypeHandlerRegistry run (which sets up a bunch of cache dictionaries for all the mappings) & then it swaps citext & text entries.

    It seems to work, but I haven't done extensive testing. Obviously reflection is not a good approach & it's likely to break with each npgsql release, but I prefer it over forking the repo.

    public static void ChangeParamMapperToCITextInsteadOfText()
    {
    	//note: this must be called when the app first launches before anything in the Npgsql namespace has been run, otherwise it's too late
    
    	var typeHandlerRegistryType = typeof(NpgsqlConnection).Assembly.GetType("Npgsql.TypeHandlerRegistry");
    	
    	object handlerTypes = typeHandlerRegistryType.GetField("HandlerTypes", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null); //Dictionary<string, TypeAndMapping>
    	object handlerTypesByNpsgqlDbType = typeHandlerRegistryType.GetField("HandlerTypesByNpsgqlDbType", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null); //Dictionary<NpgsqlDbType, TypeAndMapping>
    	Dictionary<DbType, NpgsqlDbType> dbTypeToNpgsqlDbType = (Dictionary<DbType, NpgsqlDbType>)typeHandlerRegistryType.GetField("DbTypeToNpgsqlDbType", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
    	Dictionary<Type, NpgsqlDbType> typeToNpgsqlDbType = (Dictionary<Type, NpgsqlDbType>)typeHandlerRegistryType.GetField("TypeToNpgsqlDbType", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
    
    	var handlerTypesGetItemMethod = handlerTypes.GetType().GetMethod("get_Item");
    	var handlerTypesSetItemMethod = handlerTypes.GetType().GetMethod("set_Item");
    	var handlerTypesByNpsgqlDbTypeSetItemMethod = handlerTypesByNpsgqlDbType.GetType().GetMethod("set_Item");
    
    	var oldCIText = handlerTypesGetItemMethod.Invoke(handlerTypes, new[] { "citext" });
    	var oldText = handlerTypesGetItemMethod.Invoke(handlerTypes, new[] { "text" });
    
    	var mappingField = oldText.GetType().GetField("Mapping", BindingFlags.Instance | BindingFlags.NonPublic);
    	var typeMappingAttributeType = typeof(NpgsqlConnection).Assembly.GetType("Npgsql.TypeMappingAttribute");
    	var pgNameProperty = typeMappingAttributeType.GetProperty("PgName", BindingFlags.Instance | BindingFlags.NonPublic);
    	var npgsqlDbTypeProperty = typeMappingAttributeType.GetProperty("NpgsqlDbType", BindingFlags.Instance | BindingFlags.NonPublic);
    
    	var oldTextMappingField = mappingField.GetValue(oldText);
    	var oldCITextMappingField = mappingField.GetValue(oldCIText);
    
    	pgNameProperty.SetValue(oldTextMappingField, "citext");
    	npgsqlDbTypeProperty.SetValue(oldTextMappingField, NpgsqlDbType.Citext);
    	pgNameProperty.SetValue(oldCITextMappingField, "text");
    	npgsqlDbTypeProperty.SetValue(oldCITextMappingField, NpgsqlDbType.Text);
    
    	handlerTypesSetItemMethod.Invoke(handlerTypes, new [] { "citext", oldText });
    	handlerTypesSetItemMethod.Invoke(handlerTypes, new [] { "text", oldCIText });
    	handlerTypesByNpsgqlDbTypeSetItemMethod.Invoke(handlerTypesByNpsgqlDbType, new [] { NpgsqlDbType.Citext, oldText });
    	handlerTypesByNpsgqlDbTypeSetItemMethod.Invoke(handlerTypesByNpsgqlDbType, new [] { NpgsqlDbType.Text, oldCIText });
    
    	List<DbType> dbTypesToChange = new List<DbType>() { DbType.String, DbType.StringFixedLength, DbType.AnsiString, DbType.AnsiStringFixedLength };
    	foreach (DbType dbTypeToChange in dbTypesToChange)
    	{
    		dbTypeToNpgsqlDbType[dbTypeToChange] = NpgsqlDbType.Citext;
    	}
    
    	List<Type> clrTypesToChange = new List<Type>() { typeof(string), typeof(char[]), typeof(char), typeof(ArraySegment<char>) };
    	foreach (Type clrTypeToChange in clrTypesToChange)
    	{
    		typeToNpgsqlDbType[clrTypeToChange] = NpgsqlDbType.Citext;
    	}
    }
  2. roji commented on Jan 2, 2018

    @roji
    Member

    What you're asking is already supported in the next version of Npgsql (3.3), which opens up the type handling/mapping system (#1475). I've added a test to demonstrate how this would look like.

    You can continue using the reflection hack until 3.3 is released (probably in a couple months).

  3. speige commented on Jan 2, 2018

    @speige
    Author

    Awesome. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions