NpgsqlArrayTypeMapping.cs 10.2 KB
Newer Older
S
License  
Shay Rojansky 已提交
1
#region License
2

S
License  
Shay Rojansky 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// The PostgreSQL License
//
// Copyright (C) 2016 The Npgsql Development Team
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph and the following two paragraphs appear in all copies.
//
// IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY
// FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
// ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
23

S
License  
Shay Rojansky 已提交
24 25 26
#endregion

using System;
S
Shay Rojansky 已提交
27
using System.Text;
28
using Microsoft.EntityFrameworkCore.Storage;
S
Shay Rojansky 已提交
29
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
S
Shay Rojansky 已提交
30 31
using System.Diagnostics;
using Microsoft.EntityFrameworkCore.ChangeTracking;
32

S
Shay Rojansky 已提交
33
namespace Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.Mapping
34
{
35 36 37 38 39 40
    /// <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"/>.
    /// </remarks>
S
Shay Rojansky 已提交
41
    public class NpgsqlArrayTypeMapping : RelationalTypeMapping
42
    {
S
Shay Rojansky 已提交
43
        public RelationalTypeMapping ElementMapping { get; }
S
Shay Rojansky 已提交
44

S
Shay Rojansky 已提交
45 46 47
        /// <summary>
        /// Creates the default array mapping (i.e. for the single-dimensional CLR array type)
        /// </summary>
S
Shay Rojansky 已提交
48
        public NpgsqlArrayTypeMapping(string storeType, RelationalTypeMapping elementMapping)
49
            : this(storeType, elementMapping, elementMapping.ClrType.MakeArrayType()) {}
S
Shay Rojansky 已提交
50

S
Shay Rojansky 已提交
51 52 53
        /// <summary>
        /// Creates the default array mapping (i.e. for the single-dimensional CLR array type)
        /// </summary>
S
Shay Rojansky 已提交
54
        public NpgsqlArrayTypeMapping(RelationalTypeMapping elementMapping, Type arrayType)
55
            : this(elementMapping.StoreType + "[]", elementMapping, arrayType) {}
S
Shay Rojansky 已提交
56

S
Shay Rojansky 已提交
57
        NpgsqlArrayTypeMapping(string storeType, RelationalTypeMapping elementMapping, Type arrayType)
S
Shay Rojansky 已提交
58 59 60
            : base(new RelationalTypeMappingParameters(
                new CoreTypeMappingParameters(arrayType, null, CreateComparer(elementMapping, arrayType)), storeType
            ))
61
            => ElementMapping = elementMapping;
S
Shay Rojansky 已提交
62

S
Shay Rojansky 已提交
63
        protected NpgsqlArrayTypeMapping(RelationalTypeMappingParameters parameters, RelationalTypeMapping elementMapping)
64 65
            : base(parameters)
            => ElementMapping = elementMapping;
S
Shay Rojansky 已提交
66

S
Shay Rojansky 已提交
67
        public override RelationalTypeMapping Clone(string storeType, int? size)
S
Shay Rojansky 已提交
68
            => new NpgsqlArrayTypeMapping(StoreType, ElementMapping);
S
Shay Rojansky 已提交
69

S
Shay Rojansky 已提交
70 71 72
        public override CoreTypeMapping Clone(ValueConverter converter)
            => new NpgsqlArrayTypeMapping(Parameters.WithComposedConverter(converter), ElementMapping);

S
Shay Rojansky 已提交
73
        protected override string GenerateNonNullSqlLiteral(object value)
S
Shay Rojansky 已提交
74 75 76 77
        {
            var arr = (Array)value;

            if (arr.Rank != 1)
78
                throw new NotSupportedException("Multidimensional array literals aren't supported");
S
Shay Rojansky 已提交
79 80 81 82 83 84 85 86 87

            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(",");
            }
88

89 90 91
            sb.Append("]::");
            sb.Append(ElementMapping.StoreType);
            sb.Append("[]");
S
Shay Rojansky 已提交
92 93
            return sb.ToString();
        }
S
Shay Rojansky 已提交
94 95 96 97 98 99 100 101

        #region Value Comparison

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

102 103 104
            // We currently don't support mapping multi-dimensional arrays.
            if (arrayType.GetArrayRank() != 1)
                return null;
S
Shay Rojansky 已提交
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 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152

            // 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++)
153
                    snapshot[i] = elementComparer.Snapshot(source[i]);
S
Shay Rojansky 已提交
154 155 156 157 158 159 160
                return snapshot;
            }
        }

        class SingleDimComparerWithIEquatable<TElem> : ValueComparer<TElem[]>
            where TElem : IEquatable<TElem>
        {
161
            public SingleDimComparerWithIEquatable() : base(
S
Shay Rojansky 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
                (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;
                    }
184

S
Shay Rojansky 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
                    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;
                    }
229

S
Shay Rojansky 已提交
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
                    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
252 253
    }
}