Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TypeHelpers.cs « Metadata « Data « System « System.Data.Entity « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a3f8e6394f66e9c4743eacf2a17513fdd73a71de (plain)
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
//---------------------------------------------------------------------
// <copyright file="TypeHelpers.cs" company="Microsoft">
//      Copyright(c) Microsoft Corporation.  All rights reserved.
// </copyright>
//
// @owner       [....]
// @backupOwner [....]
//---------------------------------------------------------------------

namespace System.Data.Common
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common.CommandTrees;
    using System.Data.Metadata.Edm;
    using System.Data.Objects.ELinq;
    using System.Diagnostics;
    using System.Globalization;

    /// <summary>
    /// Represents a set of static Type helpers operating on TypeMetadata
    /// </summary>
    internal static class TypeHelpers
    {
        #region Assert Types

        /// <summary>
        /// Asserts types are in Model space
        /// </summary>
        /// <param name="typeUsage"></param>
        [Conditional("DEBUG")]
        internal static void AssertEdmType(TypeUsage typeUsage)
        {
            EdmType type = typeUsage.EdmType;
            if (TypeSemantics.IsCollectionType(typeUsage))
            {
                AssertEdmType(TypeHelpers.GetElementTypeUsage(typeUsage));
            }
            else if (TypeSemantics.IsStructuralType(typeUsage) && !Helper.IsComplexType(typeUsage.EdmType) && !Helper.IsEntityType(typeUsage.EdmType))
            {
                foreach (EdmMember m in TypeHelpers.GetDeclaredStructuralMembers(typeUsage))
                {
                    AssertEdmType(m.TypeUsage);
                }
            }
            else if (TypeSemantics.IsPrimitiveType(typeUsage))
            {
                PrimitiveType pType = type as PrimitiveType;
                if (null != pType)
                {
                    if (pType.DataSpace != DataSpace.CSpace)
                        throw new NotSupportedException(String.Format(CultureInfo.InvariantCulture, "PrimitiveType must be CSpace '{0}'", typeUsage.ToString()));
                }
            }
        }

        /// <summary>
        /// Asserts querycommandtrees are in model space type terms
        /// </summary>
        /// <param name="commandTree"></param>
        [Conditional("DEBUG")]
        internal static void AssertEdmType(DbCommandTree commandTree)
        {
            DbQueryCommandTree queryCommandTree = commandTree as DbQueryCommandTree;
            if (null != queryCommandTree)
            {
                AssertEdmType(queryCommandTree.Query.ResultType);
            }
        }
        #endregion

        //
        // Type Semantics
        //
        #region Type Semantics

        /// <summary>
        /// Determines whether a given typeUsage is valid as OrderBy sort key
        /// </summary>
        /// <param name="typeUsage"></param>
        /// <returns></returns>
        internal static bool IsValidSortOpKeyType(TypeUsage typeUsage)
        {
            if (TypeSemantics.IsRowType(typeUsage))
            {
                RowType rowType = (RowType)typeUsage.EdmType;
                foreach (EdmProperty property in rowType.Properties)
                {
                    if (!IsValidSortOpKeyType(property.TypeUsage))
                    {
                        return false;
                    }
                }
                return true;
            }
            else
            {
                return TypeSemantics.IsOrderComparable(typeUsage);
            }
        }

        /// <summary>
        /// Determines whether a given typeusage is valid as GroupBy key
        /// </summary>
        /// <param name="typeUsage"></param>
        /// <returns></returns>
        internal static bool IsValidGroupKeyType(TypeUsage typeUsage)
        {
            return IsSetComparableOpType(typeUsage);
        }

        /// <summary>
        /// Determine wheter a given typeusage is valid for Distinct operator
        /// </summary>
        /// <param name="typeUsage"></param>
        /// <returns></returns>
        internal static bool IsValidDistinctOpType(TypeUsage typeUsage)
        {
            return IsSetComparableOpType(typeUsage);
        }

        /// <summary>
        /// Determine wheter a given typeusage is valid for set comparison operator such as UNION, INTERSECT and EXCEPT
        /// </summary>
        /// <param name="typeUsage"></param>
        /// <returns></returns>
        internal static bool IsSetComparableOpType(TypeUsage typeUsage)
        {
            if (Helper.IsEntityType(typeUsage.EdmType)    ||
                Helper.IsPrimitiveType(typeUsage.EdmType) ||
                Helper.IsEnumType(typeUsage.EdmType)      ||
                Helper.IsRefType(typeUsage.EdmType)        )
            {
                return true;
            }
            else if (TypeSemantics.IsRowType(typeUsage))
            {
                RowType rowType = (RowType)typeUsage.EdmType;
                foreach (EdmProperty property in rowType.Properties)
                {
                    if (!IsSetComparableOpType(property.TypeUsage))
                    {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }

        /// <summary>
        /// Returns true if typeUsage type is valid for IS [NOT] NULL (expr) operator
        /// </summary>
        /// <param name="typeUsage"></param>
        /// <returns></returns>
        internal static bool IsValidIsNullOpType(TypeUsage typeUsage)
        {
            return TypeSemantics.IsReferenceType(typeUsage) ||
                   TypeSemantics.IsEntityType(typeUsage)    ||
                   TypeSemantics.IsScalarType(typeUsage);
        }


        internal static bool IsValidInOpType(TypeUsage typeUsage)
        {
            return TypeSemantics.IsReferenceType(typeUsage) ||
                   TypeSemantics.IsEntityType(typeUsage) ||
                   TypeSemantics.IsScalarType(typeUsage);
        }

        internal static TypeUsage GetCommonTypeUsage(TypeUsage typeUsage1, TypeUsage typeUsage2)
        {
            return TypeSemantics.GetCommonType(typeUsage1, typeUsage2);
        }

        internal static TypeUsage GetCommonTypeUsage(IEnumerable<TypeUsage> types)
        {
            TypeUsage commonType = null;
            foreach (TypeUsage testType in types)
            {
                if (null == testType)
                {
                    return null;
                }

                if (null == commonType)
                {
                    commonType = testType;
                }
                else
                {
                    commonType = TypeSemantics.GetCommonType(commonType, testType);
                    if (null == commonType)
                    {
                        break;
                    }
                }
            }
            return commonType;
        }

        #endregion

        //
        // Type property extractors
        //
        #region Type property extractors
        
        internal static bool TryGetClosestPromotableType(TypeUsage fromType, out TypeUsage promotableType)
        {
            promotableType = null;
            if (Helper.IsPrimitiveType(fromType.EdmType))
            {
                PrimitiveType fromPrimitiveType = (PrimitiveType)fromType.EdmType;
                IList<PrimitiveType> promotableTypes = EdmProviderManifest.Instance.GetPromotionTypes(fromPrimitiveType);
                int index = promotableTypes.IndexOf(fromPrimitiveType);
                if (-1 != index && index + 1 < promotableTypes.Count)
                {
                    promotableType = TypeUsage.Create(promotableTypes[index + 1]);
                }
            }
            return (null != promotableType);
        }


        #endregion

        //
        // Facet Helpers
        //
        #region Facet Helpers

        internal static bool TryGetBooleanFacetValue(TypeUsage type, string facetName, out bool boolValue)
        {
            boolValue = false;
            Facet boolFacet;
            if (type.Facets.TryGetValue(facetName, false, out boolFacet) && boolFacet.Value != null)
            {
                boolValue = (bool)boolFacet.Value;
                return true;
            }

            return false;
        }

        internal static bool TryGetByteFacetValue(TypeUsage type, string facetName, out byte byteValue)
        {
            byteValue = 0;
            Facet byteFacet;
            if (type.Facets.TryGetValue(facetName, false, out byteFacet) && byteFacet.Value != null && !Helper.IsUnboundedFacetValue(byteFacet))
            {
                byteValue = (byte)byteFacet.Value;
                return true;
            }

            return false;
        }

        internal static bool TryGetIntFacetValue(TypeUsage type, string facetName, out int intValue)
        {
            intValue = 0;
            Facet intFacet;
            if (type.Facets.TryGetValue(facetName, false, out intFacet) && intFacet.Value != null && !Helper.IsUnboundedFacetValue(intFacet) && !Helper.IsVariableFacetValue(intFacet))
            {
                intValue = (int)intFacet.Value;
                return true;
            }

            return false;
        }

        internal static bool TryGetIsFixedLength(TypeUsage type, out bool isFixedLength)
        {
            if (!TypeSemantics.IsPrimitiveType(type, PrimitiveTypeKind.String) &&
                !TypeSemantics.IsPrimitiveType(type, PrimitiveTypeKind.Binary))
            {
                isFixedLength = false;
                return false;
            }

            // Binary and String MaxLength facets share the same name
            return TypeHelpers.TryGetBooleanFacetValue(type, DbProviderManifest.FixedLengthFacetName, out isFixedLength);
        }

        internal static bool TryGetIsUnicode(TypeUsage type, out bool isUnicode)
        {
            if (!TypeSemantics.IsPrimitiveType(type, PrimitiveTypeKind.String))
            {
                isUnicode = false;
                return false;
            }

            return TypeHelpers.TryGetBooleanFacetValue(type, DbProviderManifest.UnicodeFacetName, out isUnicode);
        }

        internal static bool IsFacetValueConstant(TypeUsage type, string facetName)
        {
            // Binary and String FixedLength facets share the same name
            return Helper.GetFacet(((PrimitiveType)type.EdmType).FacetDescriptions, facetName).IsConstant;
        }

        internal static bool TryGetMaxLength(TypeUsage type, out int maxLength)
        {
            if (!TypeSemantics.IsPrimitiveType(type, PrimitiveTypeKind.String) &&
                !TypeSemantics.IsPrimitiveType(type, PrimitiveTypeKind.Binary))
            {
                maxLength = 0;
                return false;
            }

            // Binary and String FixedLength facets share the same name
            return TypeHelpers.TryGetIntFacetValue(type, DbProviderManifest.MaxLengthFacetName, out maxLength);
        }

        internal static bool TryGetPrecision(TypeUsage type, out byte precision)
        {
            if (!TypeSemantics.IsPrimitiveType(type, PrimitiveTypeKind.Decimal))
            {
                precision = 0;
                return false;
            }

            return TypeHelpers.TryGetByteFacetValue(type, DbProviderManifest.PrecisionFacetName, out precision);
        }

        internal static bool TryGetScale(TypeUsage type, out byte scale)
        {
            if (!TypeSemantics.IsPrimitiveType(type, PrimitiveTypeKind.Decimal))
            {
                scale = 0;
                return false;
            }

            return TypeHelpers.TryGetByteFacetValue(type, DbProviderManifest.ScaleFacetName, out scale);
        }

        internal static bool TryGetPrimitiveTypeKind(TypeUsage type, out PrimitiveTypeKind typeKind)
        {
            if (type != null && type.EdmType != null && type.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType)
            {
                typeKind = ((PrimitiveType)type.EdmType).PrimitiveTypeKind;
                return true;
            }

            typeKind = default(PrimitiveTypeKind);
            return false;
        }

        #endregion

        //
        // Type Constructors
        //
        #region Type Constructors
        internal static CollectionType CreateCollectionType(TypeUsage elementType)
        {
            return new CollectionType(elementType);
        }

        internal static TypeUsage CreateCollectionTypeUsage(TypeUsage elementType)
        {
            return CreateCollectionTypeUsage(elementType, false /* readOnly */ );
        }

        internal static TypeUsage CreateCollectionTypeUsage(TypeUsage elementType, bool readOnly)
        {
            return TypeUsage.Create(new CollectionType(elementType));
        }

        internal static RowType CreateRowType(IEnumerable<KeyValuePair<string, TypeUsage>> columns)
        {
            return CreateRowType(columns, null);
        }

        internal static RowType CreateRowType(IEnumerable<KeyValuePair<string, TypeUsage>> columns, InitializerMetadata initializerMetadata)
        {
            List<EdmProperty> rowElements = new List<EdmProperty>();
            foreach (KeyValuePair<string, TypeUsage> kvp in columns)
            {
                rowElements.Add(new EdmProperty(kvp.Key, kvp.Value));
            }
            return new RowType(rowElements, initializerMetadata);
        }

        internal static TypeUsage CreateRowTypeUsage(IEnumerable<KeyValuePair<string, TypeUsage>> columns, bool readOnly)
        {
            return TypeUsage.Create(CreateRowType(columns));
        }

        internal static RefType CreateReferenceType(EntityTypeBase entityType)
        {
            return new RefType((EntityType)entityType);
        }

        internal static TypeUsage CreateReferenceTypeUsage(EntityType entityType)
        {
            return TypeUsage.Create(CreateReferenceType(entityType));
        }

        /// <summary>
        /// Creates metadata for a new row type with column names and types based on the key members of the specified Entity type
        /// </summary>
        /// <param name="entityType">The Entity type that provides the Key members on which the column names and types of the new row type will be based</param>
        /// <returns>A new RowType info with column names and types corresponding to the Key members of the specified Entity type</returns>
        internal static RowType CreateKeyRowType(EntityTypeBase entityType)
        {
            IEnumerable<EdmMember> entityKeys = entityType.KeyMembers;
            if (null == entityKeys)
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_Metadata_EntityTypeNullKeyMembersInvalid, "entityType");
            }

            List<KeyValuePair<string, TypeUsage>> resultCols = new List<KeyValuePair<string, TypeUsage>>();
            //int idx = 0;
            foreach (EdmProperty keyProperty in entityKeys)
            {
                //this.CheckMember(keyProperty, "property", CommandTreeUtils.FormatIndex("entityType.KeyMembers", idx++));
                resultCols.Add(new KeyValuePair<string, TypeUsage>(keyProperty.Name, Helper.GetModelTypeUsage(keyProperty)));
            }

            if (resultCols.Count < 1)
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_Metadata_EntityTypeEmptyKeyMembersInvalid, "entityType");
            }

            return TypeHelpers.CreateRowType(resultCols);
        }

        /// <summary>
        /// Gets primitive type usage for <paramref name="scalarType"/>.
        /// </summary>
        /// <param name="scalarType">Primitive or enum type usage.</param>
        /// <returns>
        /// Primitive type usage for <paramref name="scalarType"/>.
        /// </returns>
        /// <remarks>
        /// For enum types a new type usage based on the underlying type will be created. For primitive types
        /// the value passed to the function will be returned.
        /// </remarks>
        internal static TypeUsage GetPrimitiveTypeUsageForScalar(TypeUsage scalarType)
        {
            Debug.Assert(scalarType != null, "scalarType != null");
            Debug.Assert(TypeSemantics.IsScalarType(scalarType), "Primitive or enum type expected.");

            return TypeSemantics.IsEnumerationType(scalarType) ?
                CreateEnumUnderlyingTypeUsage(scalarType) :
                scalarType;
        }

        /// <summary>
        /// Factory method for creating a type usage for underlying type of enum type usage.
        /// </summary>
        /// <param name="enumTypeUsage">Enum type usage used to create an underlying type usage of.</param>
        /// <returns>Type usage for the underlying enum type.</returns>
        internal static TypeUsage CreateEnumUnderlyingTypeUsage(TypeUsage enumTypeUsage)
        {
            Debug.Assert(enumTypeUsage != null, "enumTypeUsage != null");
            Debug.Assert(TypeSemantics.IsEnumerationType(enumTypeUsage), "enumTypeUsage is not an enumerated type");

            return TypeUsage.Create(Helper.GetUnderlyingEdmTypeForEnumType(enumTypeUsage.EdmType), enumTypeUsage.Facets);
        }

        /// <summary>
        /// Factory method for creating a type usage for underlying union type of spatial type usage.
        /// </summary>
        /// <param name="spatialTypeUsage">Spatial type usage used to create a union type usage of.</param>
        /// <returns>Type usage for the spatial union type of the correct topology.</returns>
        internal static TypeUsage CreateSpatialUnionTypeUsage(TypeUsage spatialTypeUsage)
        {
            Debug.Assert(spatialTypeUsage != null, "spatialTypeUsage != null");
            Debug.Assert(TypeSemantics.IsStrongSpatialType(spatialTypeUsage), "spatialTypeUsage is not a strong spatial type");
            return TypeUsage.Create(Helper.GetSpatialNormalizedPrimitiveType(spatialTypeUsage.EdmType), spatialTypeUsage.Facets);
        }

        #endregion

        //
        // Type extractors
        //
        #region Type Extractors

        /// <summary>
        /// Retrieves Properties and/or RelationshipEnds declared by the specified type or any base type.
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        internal static IBaseList<EdmMember> GetAllStructuralMembers(TypeUsage type)
        {
            return GetAllStructuralMembers(type.EdmType);
        }

        internal static IBaseList<EdmMember> GetAllStructuralMembers(EdmType edmType)
        {
            System.Diagnostics.Debug.Assert(edmType != null);
            switch (edmType.BuiltInTypeKind)
            {
                case BuiltInTypeKind.AssociationType:
                    return (IBaseList<EdmMember>)((AssociationType)edmType).AssociationEndMembers;
                case BuiltInTypeKind.ComplexType:
                    return (IBaseList<EdmMember>)((ComplexType)edmType).Properties;
                case BuiltInTypeKind.EntityType:
                    return (IBaseList<EdmMember>)((EntityType)edmType).Properties;
                case BuiltInTypeKind.RowType:
                    return (IBaseList<EdmMember>)((RowType)edmType).Properties;
                default:
                    return EmptyArrayEdmProperty;
            }
        }

        /// <summary>
        /// Retrieves Properties and/or RelationshipEnds declared by (and ONLY by) the specified type.
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        internal static IEnumerable GetDeclaredStructuralMembers(TypeUsage type)
        {
            return GetDeclaredStructuralMembers(type.EdmType);
        }

        /// <summary>
        /// Retrieves Properties and/or RelationshipEnds declared by (and ONLY by) the specified type.
        /// </summary>
        /// <param name="edmType"></param>
        /// <returns></returns>
        internal static IEnumerable GetDeclaredStructuralMembers(EdmType edmType)
        {
            switch (edmType.BuiltInTypeKind)
            {
                case BuiltInTypeKind.AssociationType:
                    return ((AssociationType)edmType).GetDeclaredOnlyMembers<AssociationEndMember>();
                case BuiltInTypeKind.ComplexType:
                    return ((ComplexType)edmType).GetDeclaredOnlyMembers<EdmProperty>();
                case BuiltInTypeKind.EntityType:
                    return ((EntityType)edmType).GetDeclaredOnlyMembers<EdmProperty>();
                case BuiltInTypeKind.RowType:
                    return ((RowType)edmType).GetDeclaredOnlyMembers<EdmProperty>();
                default:
                    return EmptyArrayEdmProperty;
            }
        }

        internal static readonly ReadOnlyMetadataCollection<EdmMember> EmptyArrayEdmMember = new ReadOnlyMetadataCollection<EdmMember>(new MetadataCollection<EdmMember>().SetReadOnly());
        internal static readonly FilteredReadOnlyMetadataCollection<EdmProperty, EdmMember> EmptyArrayEdmProperty = new FilteredReadOnlyMetadataCollection<EdmProperty, EdmMember>(EmptyArrayEdmMember, null);

        internal static ReadOnlyMetadataCollection<EdmProperty> GetProperties(TypeUsage typeUsage)
        {
            return GetProperties(typeUsage.EdmType);
        }

        internal static ReadOnlyMetadataCollection<EdmProperty> GetProperties(EdmType edmType)
        {
            switch (edmType.BuiltInTypeKind)
            {
                case BuiltInTypeKind.ComplexType:
                    return ((ComplexType)edmType).Properties;
                case BuiltInTypeKind.EntityType:
                    return ((EntityType)edmType).Properties;
                case BuiltInTypeKind.RowType:
                    return ((RowType)edmType).Properties;
                default:
                    return EmptyArrayEdmProperty;
            }
        }

        internal static TypeUsage GetElementTypeUsage(TypeUsage type)
        {
            if (TypeSemantics.IsCollectionType(type))
            {
                return ((CollectionType)type.EdmType).TypeUsage;
            }
            else if (TypeSemantics.IsReferenceType(type))
            {
                return TypeUsage.Create(((RefType)type.EdmType).ElementType);
            }

            return null;
        }

        /// <summary>
        /// Returns row type if supplied function is a tvf returning Collection(RowType), otherwise null.
        /// </summary>
        internal static RowType GetTvfReturnType(EdmFunction tvf)
        {
            if (tvf.ReturnParameter != null && TypeSemantics.IsCollectionType(tvf.ReturnParameter.TypeUsage))
            {
                var expectedElementTypeUsage = ((CollectionType)tvf.ReturnParameter.TypeUsage.EdmType).TypeUsage;
                if (TypeSemantics.IsRowType(expectedElementTypeUsage))
                {
                    return (RowType)expectedElementTypeUsage.EdmType;
                }
            }
            return null;
        }

        //
        // Element type
        //
        internal static bool TryGetCollectionElementType(TypeUsage type, out TypeUsage elementType)
        {
            CollectionType collectionType;
            if (TypeHelpers.TryGetEdmType<CollectionType>(type, out collectionType))
            {
                elementType = collectionType.TypeUsage;
                return (elementType != null);
            }

            elementType = null;
            return false;
        }

        /// <summary>
        /// If the type refered to by the TypeUsage is a RefType, extracts the EntityType and returns true,
        /// otherwise returns false.
        /// </summary>
        /// <param name="type">TypeUsage that may or may not refer to a RefType</param>
        /// <param name="referencedEntityType">Non-null if the TypeUsage refers to a RefType, null otherwise</param>
        /// <returns>True if the TypeUsage refers to a RefType, false otherwise</returns>
        internal static bool TryGetRefEntityType(TypeUsage type, out EntityType referencedEntityType)
        {
            RefType refType;
            if (TryGetEdmType<RefType>(type, out refType) &&
                Helper.IsEntityType(refType.ElementType))
            {
                referencedEntityType = (EntityType)refType.ElementType;
                return true;
            }

            referencedEntityType = null;
            return false;
        }

        internal static TEdmType GetEdmType<TEdmType>(TypeUsage typeUsage)
            where TEdmType : EdmType
        {
            return (TEdmType)typeUsage.EdmType;
        }

        internal static bool TryGetEdmType<TEdmType>(TypeUsage typeUsage, out TEdmType type)
            where TEdmType : EdmType
        {
            type = typeUsage.EdmType as TEdmType;
            return (type != null);
        }
        #endregion

        //
        // Misc
        //
        #region Misc
        internal static TypeUsage GetReadOnlyType(TypeUsage type)
        {
            if (!(type.IsReadOnly))
            {
                type.SetReadOnly();
            }
            return type;
        }

        //
        // Type Description
        //

        internal static string GetFullName(TypeUsage type)
        {
            return type.ToString();
        }
                
        internal static string GetFullName(EdmType type)
        {
            return GetFullName(type.NamespaceName, type.Name);
        }

        internal static string GetFullName(EntitySetBase entitySet)
        {
            Debug.Assert(entitySet.EntityContainer != null, "entitySet.EntityContainer is null");
            return GetFullName(entitySet.EntityContainer.Name, entitySet.Name);
        }
                
        internal static string GetFullName(string qualifier, string name)
        {
            if (string.IsNullOrEmpty(qualifier))
            {
                return string.Format(CultureInfo.InvariantCulture, "{0}", name);
            }
            else
            {
                return string.Format(CultureInfo.InvariantCulture, "{0}.{1}", qualifier, name);
            }
        }

        /// <summary>
        /// Converts the given CLR type into a DbType
        /// </summary>
        /// <param name="clrType">The CLR type to convert</param>
        /// <returns></returns>
        internal static DbType ConvertClrTypeToDbType(Type clrType)
        {
            switch (Type.GetTypeCode(clrType))
            {
                case TypeCode.Empty:
                    throw EntityUtil.InvalidDataType(TypeCode.Empty);

                case TypeCode.Object:
                    if (clrType == typeof(System.Byte[]))
                    {
                        return DbType.Binary;
                    }
                    if (clrType == typeof(System.Char[]))
                    {
                        // Always treat char and char[] as string
                        return DbType.String;
                    }
                    else if (clrType == typeof(System.Guid))
                    {
                        return DbType.Guid;
                    }
                    else if (clrType == typeof(System.TimeSpan))
                    {
                        return DbType.Time;
                    }
                    else if (clrType == typeof(System.DateTimeOffset))
                    {
                        return DbType.DateTimeOffset;
                    }

                    return DbType.Object;

                case TypeCode.DBNull:
                    return DbType.Object;
                case TypeCode.Boolean:
                    return DbType.Boolean;
                case TypeCode.SByte:
                    return DbType.SByte;
                case TypeCode.Byte:
                    return DbType.Byte;
                case TypeCode.Char:
                    // Always treat char and char[] as string
                    return DbType.String;
                case TypeCode.Int16:
                    return DbType.Int16;
                case TypeCode.UInt16:
                    return DbType.UInt16;
                case TypeCode.Int32:
                    return DbType.Int32;
                case TypeCode.UInt32:
                    return DbType.UInt32;
                case TypeCode.Int64:
                    return DbType.Int64;
                case TypeCode.UInt64:
                    return DbType.UInt64;
                case TypeCode.Single:
                    return DbType.Single;
                case TypeCode.Double:
                    return DbType.Double;
                case TypeCode.Decimal:
                    return DbType.Decimal;
                case TypeCode.DateTime:
                    return DbType.DateTime;
                case TypeCode.String:
                    return DbType.String;
                default:
                    throw EntityUtil.UnknownDataTypeCode(clrType, Type.GetTypeCode(clrType));
            }
        }

        internal static bool IsIntegerConstant(TypeUsage valueType, object value, long expectedValue)
        {
            if (!TypeSemantics.IsIntegerNumericType(valueType))
            {
                return false;
            }

            if (null == value)
            {
                return false;
            }

            PrimitiveType intType = (PrimitiveType)valueType.EdmType;
            switch (intType.PrimitiveTypeKind)
            {
                case PrimitiveTypeKind.Byte:
                    return (expectedValue == (byte)value);

                case PrimitiveTypeKind.Int16:
                    return (expectedValue == (short)value);

                case PrimitiveTypeKind.Int32:
                    return (expectedValue == (int)value);

                case PrimitiveTypeKind.Int64:
                    return (expectedValue == (long)value);

                case PrimitiveTypeKind.SByte:
                    return (expectedValue == (sbyte)value);

                default:
                    {
                        Debug.Assert(false, "Integer primitive type was not one of Byte, Int16, Int32, Int64, SByte?");
                        return false;
                    }
            }
        }

        /// <summary>
        /// returns a Typeusage 
        /// </summary>
        /// <param name="primitiveTypeKind"></param>
        /// <returns></returns>
        static internal TypeUsage GetLiteralTypeUsage(PrimitiveTypeKind primitiveTypeKind)
        {
            // all clr strings by default are unicode
            return GetLiteralTypeUsage(primitiveTypeKind, true /* unicode */);
        }

        static internal TypeUsage GetLiteralTypeUsage(PrimitiveTypeKind primitiveTypeKind, bool isUnicode)
        {
            TypeUsage typeusage;
            PrimitiveType primitiveType = EdmProviderManifest.Instance.GetPrimitiveType(primitiveTypeKind);
            switch (primitiveTypeKind)
            {
                case PrimitiveTypeKind.String:
                    typeusage = TypeUsage.Create(primitiveType,
                        new FacetValues{ Unicode = isUnicode, MaxLength = TypeUsage.DefaultMaxLengthFacetValue, FixedLength = false, Nullable = false});
                    break;

                default:
                    typeusage = TypeUsage.Create(primitiveType,
                        new FacetValues{ Nullable = false });
                    break;
            }
            return typeusage;
        }

        #endregion

        #region EdmFunction Helpers
        internal static bool IsCanonicalFunction(EdmFunction function)
        {
            bool isCanonicalFunction = (function.DataSpace == DataSpace.CSpace && function.NamespaceName == EdmConstants.EdmNamespace);

            Debug.Assert(!isCanonicalFunction || (isCanonicalFunction && !function.HasUserDefinedBody),
                "Canonical function '" + function.FullName + "' can not have a user defined body");

            return isCanonicalFunction;
        }
        #endregion
    }
}