File: DataMapper.cs

package info (click to toggle)
mono 4.6.2.7+dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (214 lines) | stat: -rw-r--r-- 9,427 bytes parent folder | download | duplicates (2)
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
208
209
210
211
212
213
214
#region MIT license
// 
// MIT license
//
// Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// 
#endregion

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Reflection;

using DbLinq.Data.Linq.Sugar.Expressions;

#if MONO_STRICT
using System.Data.Linq;
#else
using DbLinq.Data.Linq;
#endif

namespace DbLinq.Data.Linq.Sugar.Implementation
{
    internal class DataMapper : IDataMapper
    {
        /// <summary>
        /// Returns a table given a type, or null if the type is not mapped
        /// </summary>
        /// <param name="tableType"></param>
        /// <param name="dataContext"></param>
        /// <returns></returns>
        public virtual string GetTableName(Type tableType, DataContext dataContext)
        {
            var tableDescription = dataContext.Mapping.GetTable(tableType);
            if (tableDescription != null)
                return tableDescription.TableName;
            return null;
        }

        public virtual string GetColumnName(TableExpression tableExpression, MemberInfo memberInfo, DataContext dataContext)
        {
            return GetColumnName(tableExpression.Type, memberInfo, dataContext);
        }

        public virtual string GetColumnName(Type tableType, MemberInfo memberInfo, DataContext dataContext)
        {
            var tableDescription = dataContext.Mapping.GetTable(tableType);
            var columnDescription = tableDescription.RowType.GetDataMember(memberInfo);
            if (columnDescription != null)
                return columnDescription.MappedName;
            return null;
        }

        public virtual IList<MemberInfo> GetPrimaryKeys(TableExpression tableExpression, DataContext dataContext)
        {
            var tableDescription = dataContext.Mapping.GetTable(tableExpression.Type);
            if (tableDescription != null)
                return GetPrimaryKeys(tableDescription);
            return null;
        }

        public virtual IList<MemberInfo> GetPrimaryKeys(MetaTable tableDescription)
        {
            return (from column in tableDescription.RowType.IdentityMembers select column.Member).ToList();
        }

        /// <summary>
        /// Lists table mapped columns
        /// </summary>
        /// <param name="tableDescription"></param>
        /// <returns></returns>
        public IList<MemberInfo> GetColumns(MetaTable tableDescription)
        {
            return (from column in tableDescription.RowType.PersistentDataMembers select column.Member).ToList();
        }

        /// <summary>
        /// Returns association definition, if any
        /// </summary>
        /// <param name="thisTableExpression">The table referenced by the assocation (the type holding the member)</param>
        /// <param name="memberInfo">The memberInfo related to association</param>
        /// <param name="otherType"></param>
        /// <param name="otherKey">The keys in the associated table</param>
        /// <param name="joinType"></param>
        /// <param name="joinID"></param>
        /// <param name="dataContext"></param>
        /// <returns>ThisKey</returns>
        public virtual IList<MemberInfo> GetAssociation(TableExpression thisTableExpression, MemberInfo memberInfo, Type otherType, out IList<MemberInfo> otherKey, out TableJoinType joinType, out string joinID, DataContext dataContext)
        {
            var thisTableDescription = dataContext.Mapping.GetTable(thisTableExpression.Type);
            var thisAssociation =
                (from association in thisTableDescription.RowType.Associations
                 where association.ThisMember.Member == memberInfo
                 select association).SingleOrDefault();
            if (thisAssociation != null)
            {
                // by default, join is inner
                joinType = TableJoinType.Inner;
                joinID = thisAssociation.ThisMember.MappedName;
                if (string.IsNullOrEmpty(joinID))
                    throw Error.BadArgument("S0108: Association name is required to ensure join uniqueness");

                var otherTableDescription = dataContext.Mapping.GetTable(otherType);
                bool thisKeyHasNullables, otherKeyHasNullables;
                var thisKey = GetAssociationKeys(thisTableDescription, thisAssociation.ThisKey, dataContext,
                                                 out thisKeyHasNullables);
                otherKey = GetAssociationKeys(otherTableDescription, thisAssociation.OtherKey, dataContext,
                                              out otherKeyHasNullables);

                // we just test here the left join (since associations are symmetric,
                //        we can only find left joins here, and the otherKeyHasNullables is
                //        always equal to thisKeyHasNullables)
                if (thisKeyHasNullables)
                    joinType |= TableJoinType.LeftOuter;

                return thisKey;
            }
            otherKey = null;
            joinType = TableJoinType.Default;
            joinID = null;
            return null;
        }

        /// <summary>
        /// Enumerates Keys for a given table.
        /// Keys can be provided as input. If none provided, PKs are taken from table
        /// </summary>
        /// <param name="description"></param>
        /// <param name="keys">Keys to be used, leave empty to use PKs instead</param>
        /// <param name="dataContext"></param>
        /// <param name="hasNullableKeys">returned as true if some keys can be null (we then have an outer join)</param>
        /// <returns></returns>
        protected virtual IList<MemberInfo> GetAssociationKeys(MetaTable description, ReadOnlyCollection<MetaDataMember> keys,
                                                               DataContext dataContext, out bool hasNullableKeys)
        {
            var sourceKeys = keys;
            if (sourceKeys.Count == 0)
                sourceKeys = description.RowType.IdentityMembers;

            hasNullableKeys = false;
            var members = new List<MemberInfo>();
            foreach (var sourceKey in sourceKeys)
            {
                members.Add(sourceKey.Member);
                if (sourceKey.CanBeNull)
                    hasNullableKeys = true;
            }
            return members;
        }

        public IList<MemberInfo> GetEntitySetAssociations(Type type)
        {
            // BUG: This is ignoring External Mappings from XmlMappingSource.

            // TODO: Should be cached in a static thread safe cache.

            return type.GetProperties()
                .Where(p => p.PropertyType.IsGenericType 
                    && (p.PropertyType.GetGenericTypeDefinition() == typeof(System.Data.Linq.EntitySet<>) 
#if !MONO_STRICT
                    || p.PropertyType.GetGenericTypeDefinition() == typeof(DbLinq.Data.Linq.EntitySet<>)
#endif
                    )
                    && p.IsDefined(typeof(AssociationAttribute), true))
                .Cast<MemberInfo>().ToList();
        }

        public IList<MemberInfo> GetEntityRefAssociations(Type type)
        {
            // BUG: This is ignoring External Mappings from XmlMappingSource.

            // TODO: Should be cached in a static thread safe cache.

            List<MemberInfo> associations = new List<MemberInfo>();
            foreach (var p in type.GetProperties())
            {
                AssociationAttribute associationAttribute = p.GetCustomAttributes(typeof(AssociationAttribute), true).FirstOrDefault() as AssociationAttribute;
                if (associationAttribute != null)
                {
                    FieldInfo field = type.GetField(associationAttribute.Storage, BindingFlags.NonPublic | BindingFlags.Instance);
                    if (field != null && field.FieldType.IsGenericType &&
#if MONO_STRICT
                        field.FieldType.GetGenericTypeDefinition() == typeof(System.Data.Linq.EntityRef<>)
#else
                        field.FieldType.GetGenericTypeDefinition() == typeof(DbLinq.Data.Linq.EntityRef<>)
#endif
                        )
                        associations.Add(p);
                }
            }
            return associations;
        }
    }
}