NpgsqlArrayTypeMapping.cs 9.4 KB
Newer Older
1
using System;
S
Shay Rojansky 已提交
2
using System.Text;
3
using Microsoft.EntityFrameworkCore.Storage;
S
Shay Rojansky 已提交
4 5
using System.Diagnostics;
using Microsoft.EntityFrameworkCore.ChangeTracking;
6

S
Shay Rojansky 已提交
7
namespace Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.Mapping
8
{
9 10 11 12 13
    /// <summary>
    /// Maps PostgreSQL arrays to .NET arrays. Only single-dimensional arrays are supported.
    /// </summary>
    /// <remarks>
    /// Note that mapping PostgreSQL arrays to .NET List{T} is also supported via <see cref="NpgsqlListTypeMapping"/>.
14
    /// See: https://www.postgresql.org/docs/current/static/arrays.html
15
    /// </remarks>
S
Shay Rojansky 已提交
16
    public class NpgsqlArrayTypeMapping : RelationalTypeMapping
17
    {
18 19 20 21
        // ReSharper disable once MemberCanBePrivate.Global
        /// <summary>
        /// The relational type mapping used to initialize the array mapping.
        /// </summary>
S
Shay Rojansky 已提交
22
        public RelationalTypeMapping ElementMapping { get; }
S
Shay Rojansky 已提交
23

S
Shay Rojansky 已提交
24 25 26
        /// <summary>
        /// Creates the default array mapping (i.e. for the single-dimensional CLR array type)
        /// </summary>
27 28
        /// <param name="storeType">The database type to map.</param>
        /// <param name="elementMapping">The element type mapping.</param>
S
Shay Rojansky 已提交
29
        public NpgsqlArrayTypeMapping(string storeType, RelationalTypeMapping elementMapping)
30
            : this(storeType, elementMapping, elementMapping.ClrType.MakeArrayType()) {}
S
Shay Rojansky 已提交
31

S
Shay Rojansky 已提交
32 33 34
        /// <summary>
        /// Creates the default array mapping (i.e. for the single-dimensional CLR array type)
        /// </summary>
35 36
        /// <param name="elementMapping">The element type mapping.</param>
        /// <param name="arrayType">The array type to map.</param>
S
Shay Rojansky 已提交
37
        public NpgsqlArrayTypeMapping(RelationalTypeMapping elementMapping, Type arrayType)
38
            : this(elementMapping.StoreType + "[]", elementMapping, arrayType) {}
S
Shay Rojansky 已提交
39

S
Shay Rojansky 已提交
40
        NpgsqlArrayTypeMapping(string storeType, RelationalTypeMapping elementMapping, Type arrayType)
41
            : this(new RelationalTypeMappingParameters(
S
Shay Rojansky 已提交
42
                new CoreTypeMappingParameters(arrayType, null, CreateComparer(elementMapping, arrayType)), storeType
43
            ), elementMapping) {}
S
Shay Rojansky 已提交
44

S
Shay Rojansky 已提交
45
        protected NpgsqlArrayTypeMapping(RelationalTypeMappingParameters parameters, RelationalTypeMapping elementMapping)
46 47
            : base(parameters)
            => ElementMapping = elementMapping;
S
Shay Rojansky 已提交
48

49 50
        protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters)
            => new NpgsqlArrayTypeMapping(parameters, ElementMapping);
S
Shay Rojansky 已提交
51

S
Shay Rojansky 已提交
52
        protected override string GenerateNonNullSqlLiteral(object value)
S
Shay Rojansky 已提交
53 54 55 56
        {
            var arr = (Array)value;

            if (arr.Rank != 1)
57
                throw new NotSupportedException("Multidimensional array literals aren't supported");
S
Shay Rojansky 已提交
58 59 60 61 62 63 64 65 66

            var sb = new StringBuilder();
            sb.Append("ARRAY[");
            for (var i = 0; i < arr.Length; i++)
            {
                sb.Append(ElementMapping.GenerateSqlLiteral(arr.GetValue(i)));
                if (i < arr.Length - 1)
                    sb.Append(",");
            }
67

68 69 70
            sb.Append("]::");
            sb.Append(ElementMapping.StoreType);
            sb.Append("[]");
S
Shay Rojansky 已提交
71 72
            return sb.ToString();
        }
S
Shay Rojansky 已提交
73 74 75 76 77 78 79 80

        #region Value Comparison

        static ValueComparer CreateComparer(RelationalTypeMapping elementMapping, Type arrayType)
        {
            Debug.Assert(arrayType.IsArray);
            var elementType = arrayType.GetElementType();

81 82 83
            // We currently don't support mapping multi-dimensional arrays.
            if (arrayType.GetArrayRank() != 1)
                return null;
S
Shay Rojansky 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131

            // We use different comparer implementations based on whether we have a non-null element comparer,
            // and if not, whether the element is IEquatable<TElem>

            if (elementMapping.Comparer != null)
                return (ValueComparer)Activator.CreateInstance(
                    typeof(SingleDimComparerWithComparer<>).MakeGenericType(elementType), elementMapping);

            if (typeof(IEquatable<>).MakeGenericType(elementType).IsAssignableFrom(elementType))
                return (ValueComparer)Activator.CreateInstance(typeof(SingleDimComparerWithIEquatable<>).MakeGenericType(elementType));

            // There's no custom comparer, and the element type doesn't implement IEquatable<TElem>. We have
            // no choice but to use the non-generic Equals method.
            return (ValueComparer)Activator.CreateInstance(typeof(SingleDimComparerWithEquals<>).MakeGenericType(elementType));
        }

        class SingleDimComparerWithComparer<TElem> : ValueComparer<TElem[]>
        {
            public SingleDimComparerWithComparer(RelationalTypeMapping elementMapping) : base(
                (a, b) => Compare(a, b, (ValueComparer<TElem>)elementMapping.Comparer),
                o => o.GetHashCode(), // TODO: Need to get hash code of elements...
                source => Snapshot(source, (ValueComparer<TElem>)elementMapping.Comparer)) {}

            public override Type Type => typeof(TElem[]);

            static bool Compare(TElem[] a, TElem[] b, ValueComparer<TElem> elementComparer)
            {
                if (a.Length != b.Length)
                    return false;

                // Note: the following currently boxes every element access because ValueComparer isn't really
                // generic (see https://github.com/aspnet/EntityFrameworkCore/issues/11072)
                for (var i = 0; i < a.Length; i++)
                    if (!elementComparer.Equals(a[i], b[i]))
                        return false;

                return true;
            }

            static TElem[] Snapshot(TElem[] source, ValueComparer<TElem> elementComparer)
            {
                if (source == null)
                    return null;

                var snapshot = new TElem[source.Length];
                // Note: the following currently boxes every element access because ValueComparer isn't really
                // generic (see https://github.com/aspnet/EntityFrameworkCore/issues/11072)
                for (var i = 0; i < source.Length; i++)
132
                    snapshot[i] = elementComparer.Snapshot(source[i]);
S
Shay Rojansky 已提交
133 134 135 136 137 138 139
                return snapshot;
            }
        }

        class SingleDimComparerWithIEquatable<TElem> : ValueComparer<TElem[]>
            where TElem : IEquatable<TElem>
        {
140
            public SingleDimComparerWithIEquatable() : base(
S
Shay Rojansky 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
                (a, b) => Compare(a, b),
                o => o.GetHashCode(), // TODO: Need to get hash code of elements...
                source => DoSnapshot(source)) {}

            public override Type Type => typeof(TElem[]);

            static bool Compare(TElem[] a, TElem[] b)
            {
                if (a.Length != b.Length)
                    return false;

                for (var i = 0; i < a.Length; i++)
                {
                    var elem1 = a[i];
                    var elem2 = b[i];
                    // Note: the following null checks are elided if TElem is a value type
                    if (elem1 == null)
                    {
                        if (elem2 == null)
                            continue;
                        return false;
                    }
163

S
Shay Rojansky 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
                    if (!elem1.Equals(elem2))
                        return false;
                }

                return true;
            }

            static TElem[] DoSnapshot(TElem[] source)
            {
                if (source == null)
                    return null;
                var snapshot = new TElem[source.Length];
                for (var i = 0; i < source.Length; i++)
                    snapshot[i] = source[i];
                return snapshot;
            }
        }

        class SingleDimComparerWithEquals<TElem> : ValueComparer<TElem[]>
        {
            public SingleDimComparerWithEquals() : base(
                (a, b) => Compare(a, b),
                o => o.GetHashCode(), // TODO: Need to get hash code of elements...
                source => DoSnapshot(source)) {}

            public override Type Type => typeof(TElem[]);

            static bool Compare(TElem[] a, TElem[] b)
            {
                if (a.Length != b.Length)
                    return false;

                // Note: the following currently boxes every element access because ValueComparer isn't really
                // generic (see https://github.com/aspnet/EntityFrameworkCore/issues/11072)
                for (var i = 0; i < a.Length; i++)
                {
                    var elem1 = a[i];
                    var elem2 = b[i];
                    if (elem1 == null)
                    {
                        if (elem2 == null)
                            continue;
                        return false;
                    }
208

S
Shay Rojansky 已提交
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
                    if (!elem1.Equals(elem2))
                        return false;
                }

                return true;
            }

            static TElem[] DoSnapshot(TElem[] source)
            {
                if (source == null)
                    return null;

                var snapshot = new TElem[source.Length];
                // Note: the following currently boxes every element access because ValueComparer isn't really
                // generic (see https://github.com/aspnet/EntityFrameworkCore/issues/11072)
                for (var i = 0; i < source.Length; i++)
                    snapshot[i] = source[i];
                return snapshot;
            }
        }

        #endregion Value Comparison
231 232
    }
}