Skip to content

Commit a47f23c

Browse files
jjonesczmgravell
authored andcommitted
Handle PostgreSQL chars correctly (#1326)
* Handle char correctly * Add PostgreSQL char test * Test for string before testing for char
1 parent e6f6350 commit a47f23c

File tree

2 files changed

+36
-4
lines changed

2 files changed

+36
-4
lines changed

Dapper.Tests/Providers/PostgresqlTests.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,28 @@ public void TestPostgresqlArrayParameters()
5656
}
5757
}
5858

59+
private class CharTable
60+
{
61+
public int Id { get; set; }
62+
public char CharColumn { get; set; }
63+
}
64+
65+
[FactPostgresql]
66+
public void TestPostgresqlChar()
67+
{
68+
using (var conn = GetOpenNpgsqlConnection())
69+
{
70+
var transaction = conn.BeginTransaction();
71+
conn.Execute("create table chartable (id serial not null, charcolumn \"char\" not null);");
72+
conn.Execute("insert into chartable(charcolumn) values('a');");
73+
74+
var r = conn.Query<CharTable>("select * from chartable");
75+
Assert.Single(r);
76+
Assert.Equal('a', r.Single().CharColumn);
77+
transaction.Rollback();
78+
}
79+
}
80+
5981
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
6082
public class FactPostgresqlAttribute : FactAttribute
6183
{

Dapper/SqlMapper.cs

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1877,8 +1877,13 @@ public static char ReadChar(object value)
18771877
{
18781878
if (value == null || value is DBNull) throw new ArgumentNullException(nameof(value));
18791879
var s = value as string;
1880-
if (s == null || s.Length != 1) throw new ArgumentException("A single-character was expected", nameof(value));
1881-
return s[0];
1880+
if (s == null)
1881+
{
1882+
var c = value as char?;
1883+
if (c != null) return c.Value;
1884+
}
1885+
else if (s.Length == 1) return s[0];
1886+
throw new ArgumentException("A single-character was expected", nameof(value));
18821887
}
18831888

18841889
/// <summary>
@@ -1892,8 +1897,13 @@ public static char ReadChar(object value)
18921897
{
18931898
if (value == null || value is DBNull) return null;
18941899
var s = value as string;
1895-
if (s == null || s.Length != 1) throw new ArgumentException("A single-character was expected", nameof(value));
1896-
return s[0];
1900+
if (s == null)
1901+
{
1902+
var c = value as char?;
1903+
if (c != null) return c;
1904+
}
1905+
else if (s.Length == 1) return s[0];
1906+
throw new ArgumentException("A single-character was expected", nameof(value));
18971907
}
18981908

18991909
/// <summary>

0 commit comments

Comments
 (0)