Repository navigation
Closed
Milestone
Description
It would be great if we can create our own TypeHandler and optionally specify a custom Dictionary<Type,TypeHandler> for a NpgsqlCommand that will override any global/connection wide mapping.
It will solve a couple of problems I'm currently having:
- Mapping smallint composite field to C# byte property.
- MapComposite (non global) seems to retain mapping across connection instance when connection pooling is enabled.
Steps to reproduce
Sql definition
create type person as ( id int, num SMALLINT);
create function getperson(out result person) LANGUAGE plpgsql
as $$
BEGIN
result = ROW(1,2)::person;
END
$$;
select getperson();
Code
public class Person
{
public int id { get; set; }
public int num { get; set; }
}
public class Employee : Person
{
public string job { get; set; }
}
public static Person GetComposite(Npgsql.NpgsqlConnection cnn)
{
using (var cmd = new Npgsql.NpgsqlCommand("select getperson()", cnn))
{
var par = new NpgsqlParameter("result",
NpgsqlTypes.NpgsqlDbType.Array | NpgsqlTypes.NpgsqlDbType.Composite)
{ Direction = ParameterDirection.Output };
cmd.Parameters.Add(par);
cmd.ExecuteNonQuery();
return (Person)par.Value;
}
}
private static NpgsqlConnection CreateOpenConnection()
{
var connectionString = "someconnection";
var cnn = new Npgsql.NpgsqlConnection(connectionString);
cnn.Open();
return cnn;
}
[TestMethod]
public void MapCompositeTests()
{
Npgsql.NpgsqlConnection.MapCompositeGlobally<Person>("person");
using(var cnn = CreateOpenConnection())
{
var person = GetComposite(cnn);
Assert.IsFalse(person is Employee);
cnn.MapComposite<Employee>("person");
var employee = (Employee)GetComposite(cnn);
}
using(var cnn2 = CreateOpenConnection())
{
var shouldBePerson= GetComposite(cnn2);
Assert.IsFalse(shouldBePerson is Employee);
}
}
The issue
If connection pooling is enabled, shouldBePerson is materialized as type Employee instead of Person.
The current workaround is to call MapComposite before each NpgsqlCommand
Further technical details
Npgsql version: 3.2.2
PostgreSQL version: 9.6
Operating system: Windows 10
Activity
[-]Custom TypeHandler and pluggable Composite mapping[/-][+]Composite mapping leaks across connections[/+]roji commentedon Jun 20, 2017
The ability to create your own type handlers is tracked by #1475, which is planned for version 3.3 - please go vote on that and contribute any thoughts.
I'm leaving this open for your second issue, about mappings leaking from one connection to another.
roji commentedon Jun 29, 2017
Yeah, unfortunately connection mappings aren't removed when the connection is closed (returned to the pool). I'm just now in the middle of redoing the whole Npgsql type mapping system to support #1475, and mappings are properly removed. As this is non-trivial to fix in 3.2 and as there's a workaround I'm going to leave this for 3.3.
roji commentedon Jul 3, 2017
Done in dev for 3.3, see test LocalMappingDontLeak