-
Notifications
You must be signed in to change notification settings - Fork 874
Expand file tree
/
Copy pathAdoSerializerHelpers.cs
More file actions
69 lines (62 loc) · 2.75 KB
/
AdoSerializerHelpers.cs
File metadata and controls
69 lines (62 loc) · 2.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Npgsql.Internal.Postgres;
using NpgsqlTypes;
namespace Npgsql.Internal;
static class AdoSerializerHelpers
{
public static PgTypeInfo GetTypeInfoForReading(Type type, PgTypeId pgTypeId, PgSerializerOptions options)
{
PgTypeInfo? typeInfo = null;
Exception? inner = null;
try
{
typeInfo = options.GetTypeInfoInternal(type, pgTypeId);
if (typeInfo is { SupportsReading: false })
typeInfo = null;
}
catch (Exception ex)
{
inner = ex;
}
return typeInfo ?? ThrowReadingNotSupported(type, options, pgTypeId, inner);
// InvalidCastException thrown to align with ADO.NET convention.
[DoesNotReturn]
static PgTypeInfo ThrowReadingNotSupported(Type? type, PgSerializerOptions options, PgTypeId pgTypeId, Exception? inner = null)
{
throw new InvalidCastException(
$"Reading{(type is null ? "" : $" as '{type.FullName}'")} is not supported for fields having DataTypeName '{options.DatabaseInfo.FindPostgresType(pgTypeId)?.DisplayName ?? "unknown"}'",
inner);
}
}
public static PgTypeInfo GetTypeInfoForWriting(Type? type, PgTypeId? pgTypeId, PgSerializerOptions options, NpgsqlDbType? npgsqlDbType = null)
{
Debug.Assert(type != typeof(object), "Parameters of type object are not supported.");
PgTypeInfo? typeInfo = null;
Exception? inner = null;
try
{
typeInfo = options.GetTypeInfoInternal(type, pgTypeId);
if (typeInfo is { SupportsWriting: false })
typeInfo = null;
}
catch (Exception ex)
{
inner = ex;
}
return typeInfo ?? ThrowWritingNotSupported(type, options, pgTypeId, npgsqlDbType, inner);
// InvalidCastException thrown to align with ADO.NET convention.
[DoesNotReturn]
static PgTypeInfo ThrowWritingNotSupported(Type? type, PgSerializerOptions options, PgTypeId? pgTypeId, NpgsqlDbType? npgsqlDbType, Exception? inner = null)
{
var pgTypeString = pgTypeId is null
? "no NpgsqlDbType or DataTypeName. Try setting one of these values to the expected database type."
: npgsqlDbType is null
? $"DataTypeName '{options.DatabaseInfo.FindPostgresType(pgTypeId.GetValueOrDefault())?.DisplayName ?? "unknown"}'"
: $"NpgsqlDbType '{npgsqlDbType}'";
throw new InvalidCastException(
$"Writing{(type is null ? "" : $" values of '{type.FullName}'")} is not supported for parameters having {pgTypeString}.", inner);
}
}
}