SqlMapper.cs 155.7 KB
Newer Older
1
/*
2 3 4
 License: http://www.apache.org/licenses/LICENSE-2.0 
 Home page: http://code.google.com/p/dapper-dot-net/

M
mgravell 已提交
5 6 7
 Note: to build on C# 3.0 + .NET 3.5, include the CSHARP30 compiler symbol (and yes,
 I know the difference between language and runtime versions; this is a compromise).
 */
8

9
using System;
M
mgravell 已提交
10 11
using System.Collections;
using System.Collections.Generic;
M
mgravell 已提交
12
using System.ComponentModel;
S
Sam Saffron 已提交
13
using System.Data;
M
mgravell 已提交
14 15 16
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
M
mgravell 已提交
17
using System.Text;
M
mgravell 已提交
18
using System.Threading;
19
using System.Text.RegularExpressions;
20
using System.Diagnostics;
S
Sam Saffron 已提交
21

22

23
namespace Dapper
S
Sam Saffron 已提交
24
{
S
Sam Saffron 已提交
25 26 27
    /// <summary>
    /// Dapper, a light weight object mapper for ADO.NET
    /// </summary>
28
    static partial class SqlMapper
S
Sam Saffron 已提交
29
    {
S
Sam Saffron 已提交
30 31 32
        /// <summary>
        /// Implement this interface to pass an arbitrary db specific set of parameters to Dapper
        /// </summary>
33
        public partial interface IDynamicParameters
S
Sam Saffron 已提交
34
        {
S
Sam Saffron 已提交
35 36 37 38 39
            /// <summary>
            /// Add all the parameters needed to the command just before it executes
            /// </summary>
            /// <param name="command">The raw command prior to execution</param>
            /// <param name="identity">Information about the query</param>
40
            void AddParameters(IDbCommand command, Identity identity);
S
Sam Saffron 已提交
41
        }
42

43 44 45 46 47 48 49 50 51 52 53 54 55
        /// <summary>
        /// Implement this interface to pass an arbitrary db specific parameter to Dapper
        /// </summary>
        public interface ICustomQueryParameter
        {
            /// <summary>
            /// Add the parameter needed to the command before it executes
            /// </summary>
            /// <param name="command">The raw command prior to execution</param>
            /// <param name="name">Parameter name</param>
            void AddParameter(IDbCommand command, string name);
        }

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
        /// <summary>
        /// Implement this interface to change default mapping of reader columns to type memebers
        /// </summary>
        public interface ITypeMap
        {
            /// <summary>
            /// Finds best constructor
            /// </summary>
            /// <param name="names">DataReader column names</param>
            /// <param name="types">DataReader column types</param>
            /// <returns>Matching constructor or default one</returns>
            ConstructorInfo FindConstructor(string[] names, Type[] types);

            /// <summary>
            /// Gets mapping for constructor parameter
            /// </summary>
            /// <param name="constructor">Constructor to resolve</param>
            /// <param name="columnName">DataReader column name</param>
            /// <returns>Mapping implementation</returns>
            IMemberMap GetConstructorParameter(ConstructorInfo constructor, string columnName);

            /// <summary>
            /// Gets member mapping for column
            /// </summary>
            /// <param name="columnName">DataReader column name</param>
            /// <returns>Mapping implementation</returns>
            IMemberMap GetMember(string columnName);
        }

        /// <summary>
        /// Implements this interface to provide custom member mapping
        /// </summary>
        public interface IMemberMap
        {
            /// <summary>
            /// Source DataReader column name
            /// </summary>
            string ColumnName { get; }

            /// <summary>
            ///  Target member type
            /// </summary>
            Type MemberType { get; }

            /// <summary>
            /// Target property
            /// </summary>
            PropertyInfo Property { get; }

            /// <summary>
            /// Target field
            /// </summary>
            FieldInfo Field { get; }

            /// <summary>
            /// Target constructor parameter
            /// </summary>
            ParameterInfo Parameter { get; }
        }

M
mgravell 已提交
116 117 118
        static Link<Type, Action<IDbCommand, bool>> bindByNameCache;
        static Action<IDbCommand, bool> GetBindByName(Type commandType)
        {
119
            if (commandType == null) return null; // GIGO
M
mgravell 已提交
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
            Action<IDbCommand, bool> action;
            if (Link<Type, Action<IDbCommand, bool>>.TryGet(bindByNameCache, commandType, out action))
            {
                return action;
            }
            var prop = commandType.GetProperty("BindByName", BindingFlags.Public | BindingFlags.Instance);
            action = null;
            ParameterInfo[] indexers;
            MethodInfo setter;
            if (prop != null && prop.CanWrite && prop.PropertyType == typeof(bool)
                && ((indexers = prop.GetIndexParameters()) == null || indexers.Length == 0)
                && (setter = prop.GetSetMethod()) != null
                )
            {
                var method = new DynamicMethod(commandType.Name + "_BindByName", null, new Type[] { typeof(IDbCommand), typeof(bool) });
                var il = method.GetILGenerator();
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Castclass, commandType);
                il.Emit(OpCodes.Ldarg_1);
                il.EmitCall(OpCodes.Callvirt, setter, null);
                il.Emit(OpCodes.Ret);
                action = (Action<IDbCommand, bool>)method.CreateDelegate(typeof(Action<IDbCommand, bool>));
            }
            // cache it            
            Link<Type, Action<IDbCommand, bool>>.TryAdd(ref bindByNameCache, commandType, ref action);
            return action;
        }
        /// <summary>
        /// This is a micro-cache; suitable when the number of terms is controllable (a few hundred, for example),
        /// and strictly append-only; you cannot change existing values. All key matches are on **REFERENCE**
        /// equality. The type is fully thread-safe.
        /// </summary>
152
        partial class Link<TKey, TValue> where TKey : class
M
mgravell 已提交
153 154 155 156 157
        {
            public static bool TryGet(Link<TKey, TValue> link, TKey key, out TValue value)
            {
                while (link != null)
                {
158
                    if ((object)key == (object)link.Key)
M
mgravell 已提交
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
                    {
                        value = link.Value;
                        return true;
                    }
                    link = link.Tail;
                }
                value = default(TValue);
                return false;
            }
            public static bool TryAdd(ref Link<TKey, TValue> head, TKey key, ref TValue value)
            {
                bool tryAgain;
                do
                {
                    var snapshot = Interlocked.CompareExchange(ref head, null, null);
                    TValue found;
                    if (TryGet(snapshot, key, out found))
                    { // existing match; report the existing value instead
                        value = found;
                        return false;
                    }
                    var newNode = new Link<TKey, TValue>(key, value, snapshot);
                    // did somebody move our cheese?
                    tryAgain = Interlocked.CompareExchange(ref head, newNode, snapshot) != snapshot;
                } while (tryAgain);
                return true;
            }
            private Link(TKey key, TValue value, Link<TKey, TValue> tail)
            {
                Key = key;
                Value = value;
                Tail = tail;
            }
            public TKey Key { get; private set; }
            public TValue Value { get; private set; }
            public Link<TKey, TValue> Tail { get; private set; }
        }
196
        partial class CacheInfo
S
Sam Saffron 已提交
197
        {
198
            public DeserializerState Deserializer { get; set; }
M
mgravell 已提交
199
            public Func<IDataReader, object>[] OtherDeserializers { get; set; }
200
            public Action<IDbCommand, object> ParamReader { get; set; }
M
mgravell 已提交
201 202 203
            private int hitCount;
            public int GetHitCount() { return Interlocked.CompareExchange(ref hitCount, 0, 0); }
            public void RecordHit() { Interlocked.Increment(ref hitCount); }
S
Sam Saffron 已提交
204
        }
205 206 207 208 209 210
        static int GetColumnHash(IDataReader reader)
        {
            unchecked
            {
                int colCount = reader.FieldCount, hash = colCount;
                for (int i = 0; i < colCount; i++)
211
                {   // binding code is only interested in names - not types
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
                    object tmp = reader.GetName(i);
                    hash = (hash * 31) + (tmp == null ? 0 : tmp.GetHashCode());
                }
                return hash;
            }
        }
        struct DeserializerState
        {
            public readonly int Hash;
            public readonly Func<IDataReader, object> Func;

            public DeserializerState(int hash, Func<IDataReader, object> func)
            {
                Hash = hash;
                Func = func;
            }
        }
229

S
Sam Saffron 已提交
230 231 232
        /// <summary>
        /// Called if the query cache is purged via PurgeQueryCache
        /// </summary>
233 234 235 236 237 238
        public static event EventHandler QueryCachePurged;
        private static void OnQueryCachePurged()
        {
            var handler = QueryCachePurged;
            if (handler != null) handler(null, EventArgs.Empty);
        }
M
mgravell 已提交
239 240
#if CSHARP30
        private static readonly Dictionary<Identity, CacheInfo> _queryCache = new Dictionary<Identity, CacheInfo>();
241 242
        // note: conflicts between readers and writers are so short-lived that it isn't worth the overhead of
        // ReaderWriterLockSlim etc; a simple lock is faster
M
mgravell 已提交
243 244
        private static void SetQueryCache(Identity key, CacheInfo value)
        {
245
            lock (_queryCache) { _queryCache[key] = value; }
M
mgravell 已提交
246 247 248
        }
        private static bool TryGetQueryCache(Identity key, out CacheInfo value)
        {
249
            lock (_queryCache) { return _queryCache.TryGetValue(key, out value); }
M
mgravell 已提交
250
        }
251 252 253 254 255 256 257 258 259
        private static void PurgeQueryCacheByType(Type type)
        {
            lock (_queryCache)
            {
                var toRemove = _queryCache.Keys.Where(id => id.type == type).ToArray();
                foreach (var key in toRemove)
                    _queryCache.Remove(key);
            }
        }
M
Marc Gravell 已提交
260 261 262
        /// <summary>
        /// Purge the query cache 
        /// </summary>
263 264 265 266
        public static void PurgeQueryCache()
        {
            lock (_queryCache)
            {
267
                _queryCache.Clear();
268 269
            }
            OnQueryCachePurged();
270
        }
M
mgravell 已提交
271 272 273 274
#else
        static readonly System.Collections.Concurrent.ConcurrentDictionary<Identity, CacheInfo> _queryCache = new System.Collections.Concurrent.ConcurrentDictionary<Identity, CacheInfo>();
        private static void SetQueryCache(Identity key, CacheInfo value)
        {
275
            if (Interlocked.Increment(ref collect) == COLLECT_PER_ITEMS)
M
mgravell 已提交
276 277 278
            {
                CollectCacheGarbage();
            }
M
mgravell 已提交
279 280
            _queryCache[key] = value;
        }
M
mgravell 已提交
281 282 283 284 285 286 287 288 289 290 291 292 293 294

        private static void CollectCacheGarbage()
        {
            try
            {
                foreach (var pair in _queryCache)
                {
                    if (pair.Value.GetHitCount() <= COLLECT_HIT_COUNT_MIN)
                    {
                        CacheInfo cache;
                        _queryCache.TryRemove(pair.Key, out cache);
                    }
                }
            }
295

M
mgravell 已提交
296 297 298 299 300 301 302 303
            finally
            {
                Interlocked.Exchange(ref collect, 0);
            }
        }

        private const int COLLECT_PER_ITEMS = 1000, COLLECT_HIT_COUNT_MIN = 0;
        private static int collect;
M
mgravell 已提交
304 305
        private static bool TryGetQueryCache(Identity key, out CacheInfo value)
        {
306
            if (_queryCache.TryGetValue(key, out value))
M
mgravell 已提交
307 308 309 310 311 312
            {
                value.RecordHit();
                return true;
            }
            value = null;
            return false;
M
mgravell 已提交
313
        }
S
Sam Saffron 已提交
314

S
Sam Saffron 已提交
315 316 317
        /// <summary>
        /// Purge the query cache 
        /// </summary>
318 319 320 321
        public static void PurgeQueryCache()
        {
            _queryCache.Clear();
            OnQueryCachePurged();
322
        }
M
mgravell 已提交
323

324 325 326 327 328 329 330 331 332 333
        private static void PurgeQueryCacheByType(Type type)
        {
            foreach (var entry in _queryCache)
            {
                CacheInfo cache;
                if (entry.Key.type == type)
                    _queryCache.TryRemove(entry.Key, out cache);
            }
        }

S
Sam Saffron 已提交
334 335 336 337
        /// <summary>
        /// Return a count of all the cached queries by dapper
        /// </summary>
        /// <returns></returns>
M
mgravell 已提交
338 339 340 341 342
        public static int GetCachedSQLCount()
        {
            return _queryCache.Count;
        }

S
Sam Saffron 已提交
343 344 345 346 347
        /// <summary>
        /// Return a list of all the queries cached by dapper
        /// </summary>
        /// <param name="ignoreHitCountAbove"></param>
        /// <returns></returns>
M
mgravell 已提交
348 349 350 351 352 353 354
        public static IEnumerable<Tuple<string, string, int>> GetCachedSQL(int ignoreHitCountAbove = int.MaxValue)
        {
            var data = _queryCache.Select(pair => Tuple.Create(pair.Key.connectionString, pair.Key.sql, pair.Value.GetHitCount()));
            if (ignoreHitCountAbove < int.MaxValue) data = data.Where(tuple => tuple.Item3 <= ignoreHitCountAbove);
            return data;
        }

S
Sam Saffron 已提交
355 356 357 358
        /// <summary>
        /// Deep diagnostics only: find any hash collisions in the cache
        /// </summary>
        /// <returns></returns>
359
        public static IEnumerable<Tuple<int, int>> GetHashCollissions()
M
mgravell 已提交
360 361
        {
            var counts = new Dictionary<int, int>();
362
            foreach (var key in _queryCache.Keys)
M
mgravell 已提交
363 364
            {
                int count;
365
                if (!counts.TryGetValue(key.hashCode, out count))
M
mgravell 已提交
366 367
                {
                    counts.Add(key.hashCode, 1);
368 369
                }
                else
M
mgravell 已提交
370 371 372 373 374 375 376 377 378
                {
                    counts[key.hashCode] = count + 1;
                }
            }
            return from pair in counts
                   where pair.Value > 1
                   select Tuple.Create(pair.Key, pair.Value);

        }
M
mgravell 已提交
379
#endif
M
mgravell 已提交
380 381 382


        static readonly Dictionary<Type, DbType> typeMap;
383

S
Sam Saffron 已提交
384 385
        static SqlMapper()
        {
M
mgravell 已提交
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
            typeMap = new Dictionary<Type, DbType>();
            typeMap[typeof(byte)] = DbType.Byte;
            typeMap[typeof(sbyte)] = DbType.SByte;
            typeMap[typeof(short)] = DbType.Int16;
            typeMap[typeof(ushort)] = DbType.UInt16;
            typeMap[typeof(int)] = DbType.Int32;
            typeMap[typeof(uint)] = DbType.UInt32;
            typeMap[typeof(long)] = DbType.Int64;
            typeMap[typeof(ulong)] = DbType.UInt64;
            typeMap[typeof(float)] = DbType.Single;
            typeMap[typeof(double)] = DbType.Double;
            typeMap[typeof(decimal)] = DbType.Decimal;
            typeMap[typeof(bool)] = DbType.Boolean;
            typeMap[typeof(string)] = DbType.String;
            typeMap[typeof(char)] = DbType.StringFixedLength;
            typeMap[typeof(Guid)] = DbType.Guid;
            typeMap[typeof(DateTime)] = DbType.DateTime;
            typeMap[typeof(DateTimeOffset)] = DbType.DateTimeOffset;
J
Jakub Konecki 已提交
404
            typeMap[typeof(TimeSpan)] = DbType.Time;
M
mgravell 已提交
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
            typeMap[typeof(byte[])] = DbType.Binary;
            typeMap[typeof(byte?)] = DbType.Byte;
            typeMap[typeof(sbyte?)] = DbType.SByte;
            typeMap[typeof(short?)] = DbType.Int16;
            typeMap[typeof(ushort?)] = DbType.UInt16;
            typeMap[typeof(int?)] = DbType.Int32;
            typeMap[typeof(uint?)] = DbType.UInt32;
            typeMap[typeof(long?)] = DbType.Int64;
            typeMap[typeof(ulong?)] = DbType.UInt64;
            typeMap[typeof(float?)] = DbType.Single;
            typeMap[typeof(double?)] = DbType.Double;
            typeMap[typeof(decimal?)] = DbType.Decimal;
            typeMap[typeof(bool?)] = DbType.Boolean;
            typeMap[typeof(char?)] = DbType.StringFixedLength;
            typeMap[typeof(Guid?)] = DbType.Guid;
            typeMap[typeof(DateTime?)] = DbType.DateTime;
            typeMap[typeof(DateTimeOffset?)] = DbType.DateTimeOffset;
J
Jakub Konecki 已提交
422
            typeMap[typeof(TimeSpan?)] = DbType.Time;
S
SwissCheeze 已提交
423
            typeMap[typeof(Object)] = DbType.Object;
424
        }
425 426 427
        /// <summary>
        /// Configire the specified type to be mapped to a given db-type
        /// </summary>
428 429 430 431 432
        public static void AddTypeMap(Type type, DbType dbType)
        {
            typeMap[type] = dbType;
        }

433
        internal const string LinqBinary = "System.Data.Linq.Binary";
434
        internal static DbType LookupDbType(Type type, string name)
435
        {
436
            DbType dbType;
437 438
            var nullUnderlyingType = Nullable.GetUnderlyingType(type);
            if (nullUnderlyingType != null) type = nullUnderlyingType;
439
            if (type.IsEnum && !typeMap.ContainsKey(type))
440 441 442
            {
                type = Enum.GetUnderlyingType(type);
            }
M
mgravell 已提交
443
            if (typeMap.TryGetValue(type, out dbType))
444 445 446
            {
                return dbType;
            }
M
mgravell 已提交
447 448 449 450
            if (type.FullName == LinqBinary)
            {
                return DbType.Binary;
            }
451
            if (typeof(IEnumerable).IsAssignableFrom(type))
452
            {
453
                return DynamicParameters.EnumerableMultiParameter;
454 455
            }

456

457
            throw new NotSupportedException(string.Format("The member {0} of type {1} cannot be used as a parameter value", name, type));
S
Sam Saffron 已提交
458 459
        }

460

S
Sam Saffron 已提交
461 462 463
        /// <summary>
        /// Identity of a cached query in Dapper, used for extensability
        /// </summary>
464
        public partial class Identity : IEquatable<Identity>
S
Sam Saffron 已提交
465
        {
466 467
            internal Identity ForGrid(Type primaryType, int gridIndex)
            {
468
                return new Identity(sql, commandType, connectionString, primaryType, parametersType, null, gridIndex);
469
            }
470 471 472

            internal Identity ForGrid(Type primaryType, Type[] otherTypes, int gridIndex)
            {
473
                return new Identity(sql, commandType, connectionString, primaryType, parametersType, otherTypes, gridIndex);
474
            }
S
Sam Saffron 已提交
475 476 477 478 479
            /// <summary>
            /// Create an identity for use with DynamicParameters, internal use only
            /// </summary>
            /// <param name="type"></param>
            /// <returns></returns>
480 481
            public Identity ForDynamicParameters(Type type)
            {
482
                return new Identity(sql, commandType, connectionString, this.type, type, null, -1);
483 484
            }

485 486
            internal Identity(string sql, CommandType? commandType, IDbConnection connection, Type type, Type parametersType, Type[] otherTypes)
                : this(sql, commandType, connection.ConnectionString, type, parametersType, otherTypes, 0)
487
            { }
488
            private Identity(string sql, CommandType? commandType, string connectionString, Type type, Type parametersType, Type[] otherTypes, int gridIndex)
S
Sam Saffron 已提交
489 490
            {
                this.sql = sql;
491
                this.commandType = commandType;
492
                this.connectionString = connectionString;
S
Sam Saffron 已提交
493
                this.type = type;
S
Sam Saffron 已提交
494
                this.parametersType = parametersType;
495
                this.gridIndex = gridIndex;
M
mgravell 已提交
496 497 498
                unchecked
                {
                    hashCode = 17; // we *know* we are using this in a dictionary, so pre-compute this
499
                    hashCode = hashCode * 23 + commandType.GetHashCode();
500
                    hashCode = hashCode * 23 + gridIndex.GetHashCode();
M
mgravell 已提交
501 502
                    hashCode = hashCode * 23 + (sql == null ? 0 : sql.GetHashCode());
                    hashCode = hashCode * 23 + (type == null ? 0 : type.GetHashCode());
S
Sam Saffron 已提交
503 504
                    if (otherTypes != null)
                    {
505
                        foreach (var t in otherTypes)
S
Sam Saffron 已提交
506
                        {
507
                            hashCode = hashCode * 23 + (t == null ? 0 : t.GetHashCode());
S
Sam Saffron 已提交
508 509
                        }
                    }
510
                    hashCode = hashCode * 23 + (connectionString == null ? 0 : SqlMapper.connectionStringComparer.GetHashCode(connectionString));
S
Sam Saffron 已提交
511
                    hashCode = hashCode * 23 + (parametersType == null ? 0 : parametersType.GetHashCode());
M
mgravell 已提交
512
                }
S
Sam Saffron 已提交
513
            }
514

S
Sam Saffron 已提交
515 516 517 518 519
            /// <summary>
            /// 
            /// </summary>
            /// <param name="obj"></param>
            /// <returns></returns>
S
Sam Saffron 已提交
520 521 522 523
            public override bool Equals(object obj)
            {
                return Equals(obj as Identity);
            }
S
Sam Saffron 已提交
524 525 526
            /// <summary>
            /// The sql
            /// </summary>
527
            public readonly string sql;
S
Sam Saffron 已提交
528 529 530
            /// <summary>
            /// The command type 
            /// </summary>
531
            public readonly CommandType? commandType;
532

S
Sam Saffron 已提交
533 534 535
            /// <summary>
            /// 
            /// </summary>
536
            public readonly int hashCode, gridIndex;
537 538 539 540
            /// <summary>
            /// 
            /// </summary>
            public readonly Type type;
S
Sam Saffron 已提交
541 542 543
            /// <summary>
            /// 
            /// </summary>
544
            public readonly string connectionString;
S
Sam Saffron 已提交
545 546 547
            /// <summary>
            /// 
            /// </summary>
548
            public readonly Type parametersType;
S
Sam Saffron 已提交
549 550 551 552
            /// <summary>
            /// 
            /// </summary>
            /// <returns></returns>
S
Sam Saffron 已提交
553 554 555 556
            public override int GetHashCode()
            {
                return hashCode;
            }
S
Sam Saffron 已提交
557 558 559 560 561
            /// <summary>
            /// Compare 2 Identity objects
            /// </summary>
            /// <param name="other"></param>
            /// <returns></returns>
S
Sam Saffron 已提交
562 563
            public bool Equals(Identity other)
            {
564
                return
565 566
                    other != null &&
                    gridIndex == other.gridIndex &&
567 568
                    type == other.type &&
                    sql == other.sql &&
569
                    commandType == other.commandType &&
570
                    SqlMapper.connectionStringComparer.Equals(connectionString, other.connectionString) &&
S
Sam Saffron 已提交
571
                    parametersType == other.parametersType;
S
Sam Saffron 已提交
572 573 574
            }
        }

M
mgravell 已提交
575 576 577 578 579 580 581 582 583
#if CSHARP30
        /// <summary>
        /// Execute parameterized SQL  
        /// </summary>
        /// <returns>Number of rows affected</returns>
        public static int Execute(this IDbConnection cnn, string sql, object param)
        {
            return Execute(cnn, sql, param, null, null, null);
        }
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

        /// <summary>
        /// Execute parameterized SQL
        /// </summary>
        /// <returns>Number of rows affected</returns>
        public static int Execute(this IDbConnection cnn, string sql, object param, IDbTransaction transaction)
        {
            return Execute(cnn, sql, param, transaction, null, null);
        }

        /// <summary>
        /// Execute parameterized SQL
        /// </summary>
        /// <returns>Number of rows affected</returns>
        public static int Execute(this IDbConnection cnn, string sql, object param, CommandType commandType)
        {
            return Execute(cnn, sql, param, null, null, commandType);
        }

        /// <summary>
        /// Execute parameterized SQL
        /// </summary>
        /// <returns>Number of rows affected</returns>
        public static int Execute(this IDbConnection cnn, string sql, object param, IDbTransaction transaction, CommandType commandType)
        {
            return Execute(cnn, sql, param, transaction, null, commandType);
        }

M
mgravell 已提交
612 613 614 615 616 617 618 619 620 621 622
        /// <summary>
        /// Executes a query, returning the data typed as per T
        /// </summary>
        /// <returns>A sequence of data of the supplied type; if a basic type (int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is
        /// created per row, and a direct column-name===member-name mapping is assumed (case insensitive).
        /// </returns>
        public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param)
        {
            return Query<T>(cnn, sql, param, null, true, null, null);
        }

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
        /// <summary>
        /// Executes a query, returning the data typed as per T
        /// </summary>
        /// <returns>A sequence of data of the supplied type; if a basic type (int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is
        /// created per row, and a direct column-name===member-name mapping is assumed (case insensitive).
        /// </returns>
        public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param, IDbTransaction transaction)
        {
            return Query<T>(cnn, sql, param, transaction, true, null, null);
        }

        /// <summary>
        /// Executes a query, returning the data typed as per T
        /// </summary>
        /// <returns>A sequence of data of the supplied type; if a basic type (int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is
        /// created per row, and a direct column-name===member-name mapping is assumed (case insensitive).
        /// </returns>
        public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param, CommandType commandType)
        {
            return Query<T>(cnn, sql, param, null, true, null, commandType);
        }

        /// <summary>
        /// Executes a query, returning the data typed as per T
        /// </summary>
        /// <returns>A sequence of data of the supplied type; if a basic type (int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is
        /// created per row, and a direct column-name===member-name mapping is assumed (case insensitive).
        /// </returns>
        public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param, IDbTransaction transaction, CommandType commandType)
        {
            return Query<T>(cnn, sql, param, transaction, true, null, commandType);
        }

J
Joao Silva 已提交
656 657 658
        /// <summary>
        /// Execute a command that returns multiple result sets, and access each in turn
        /// </summary>
659
        public static GridReader QueryMultiple(this IDbConnection cnn, string sql, object param, IDbTransaction transaction)
J
Joao Silva 已提交
660 661 662 663 664 665 666
        {
            return QueryMultiple(cnn, sql, param, transaction, null, null);
        }

        /// <summary>
        /// Execute a command that returns multiple result sets, and access each in turn
        /// </summary>
667
        public static GridReader QueryMultiple(this IDbConnection cnn, string sql, object param, CommandType commandType)
J
Joao Silva 已提交
668 669 670 671 672 673 674 675 676 677 678
        {
            return QueryMultiple(cnn, sql, param, null, null, commandType);
        }

        /// <summary>
        /// Execute a command that returns multiple result sets, and access each in turn
        /// </summary>
        public static GridReader QueryMultiple(this IDbConnection cnn, string sql, object param, IDbTransaction transaction, CommandType commandType)
        {
            return QueryMultiple(cnn, sql, param, transaction, null, commandType);
        }
M
mgravell 已提交
679
#endif
S
Sam Saffron 已提交
680 681 682 683
        /// <summary>
        /// Execute parameterized SQL  
        /// </summary>
        /// <returns>Number of rows affected</returns>
M
mgravell 已提交
684 685
        public static int Execute(
#if CSHARP30
686
this IDbConnection cnn, string sql, object param, IDbTransaction transaction, int? commandTimeout, CommandType? commandType
M
mgravell 已提交
687
#else
688
this IDbConnection cnn, string sql, dynamic param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null
M
mgravell 已提交
689 690 691
#endif
)
        {
692 693
            IEnumerable multiExec = (object)param as IEnumerable;
            Identity identity;
694
            CacheInfo info = null;
695
            if (multiExec != null && !(multiExec is string))
696
            {
697 698 699
                bool isFirst = true;
                int total = 0;
                using (var cmd = SetupCommand(cnn, transaction, sql, null, null, commandTimeout, commandType))
700
                {
701 702

                    string masterSql = null;
703 704 705
                    foreach (var obj in multiExec)
                    {
                        if (isFirst)
706
                        {
707 708
                            masterSql = cmd.CommandText;
                            isFirst = false;
709
                            identity = new Identity(sql, cmd.CommandType, cnn, null, obj.GetType(), null);
710
                            info = GetCacheInfo(identity);
711
                        }
712 713 714 715 716 717 718
                        else
                        {
                            cmd.CommandText = masterSql; // because we do magic replaces on "in" etc
                            cmd.Parameters.Clear(); // current code is Add-tastic
                        }
                        info.ParamReader(cmd, obj);
                        total += cmd.ExecuteNonQuery();
719 720
                    }
                }
721
                return total;
722 723 724
            }

            // nice and simple
M
mgravell 已提交
725 726
            if ((object)param != null)
            {
727
                identity = new Identity(sql, commandType, cnn, null, (object)param == null ? null : ((object)param).GetType(), null);
M
mgravell 已提交
728 729 730
                info = GetCacheInfo(identity);
            }
            return ExecuteCommand(cnn, transaction, sql, (object)param == null ? null : info.ParamReader, (object)param, commandTimeout, commandType);
S
Sam Saffron 已提交
731
        }
M
mgravell 已提交
732
#if !CSHARP30
733
        /// <summary>
734
        /// Return a list of dynamic objects, reader is closed after the call
735
        /// </summary>
S
Sam Saffron 已提交
736
        public static IEnumerable<dynamic> Query(this IDbConnection cnn, string sql, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
737
        {
738
            return Query<DapperRow>(cnn, sql, param as object, transaction, buffered, commandTimeout, commandType);
S
Sam Saffron 已提交
739
        }
740 741 742 743
#else
        /// <summary>
        /// Return a list of dynamic objects, reader is closed after the call
        /// </summary>
744 745
        public static IEnumerable<IDictionary<string, object>> Query(this IDbConnection cnn, string sql, object param)
        {
746 747 748 749 750 751
            return Query(cnn, sql, param, null, true, null, null);
        }

        /// <summary>
        /// Return a list of dynamic objects, reader is closed after the call
        /// </summary>
752 753
        public static IEnumerable<IDictionary<string, object>> Query(this IDbConnection cnn, string sql, object param, IDbTransaction transaction)
        {
754 755 756 757 758 759
            return Query(cnn, sql, param, transaction, true, null, null);
        }

        /// <summary>
        /// Return a list of dynamic objects, reader is closed after the call
        /// </summary>
760 761
        public static IEnumerable<IDictionary<string, object>> Query(this IDbConnection cnn, string sql, object param, CommandType? commandType)
        {
762 763 764 765 766 767
            return Query(cnn, sql, param, null, true, null, commandType);
        }

        /// <summary>
        /// Return a list of dynamic objects, reader is closed after the call
        /// </summary>
768 769
        public static IEnumerable<IDictionary<string, object>> Query(this IDbConnection cnn, string sql, object param, IDbTransaction transaction, CommandType? commandType)
        {
770 771 772 773 774 775
            return Query(cnn, sql, param, transaction, true, null, commandType);
        }

        /// <summary>
        /// Return a list of dynamic objects, reader is closed after the call
        /// </summary>
776 777
        public static IEnumerable<IDictionary<string, object>> Query(this IDbConnection cnn, string sql, object param, IDbTransaction transaction, bool buffered, int? commandTimeout, CommandType? commandType)
        {
778 779
            return Query<IDictionary<string, object>>(cnn, sql, param, transaction, buffered, commandTimeout, commandType);
        }
M
mgravell 已提交
780
#endif
781

M
mgravell 已提交
782 783 784
        /// <summary>
        /// Executes a query, returning the data typed as per T
        /// </summary>
S
Sam Saffron 已提交
785
        /// <remarks>the dynamic param may seem a bit odd, but this works around a major usability issue in vs, if it is Object vs completion gets annoying. Eg type new [space] get new object</remarks>
M
mgravell 已提交
786 787 788
        /// <returns>A sequence of data of the supplied type; if a basic type (int, string, etc) is queried then the data from the first column in assumed, otherwise an instance is
        /// created per row, and a direct column-name===member-name mapping is assumed (case insensitive).
        /// </returns>
M
mgravell 已提交
789 790
        public static IEnumerable<T> Query<T>(
#if CSHARP30
791
this IDbConnection cnn, string sql, object param, IDbTransaction transaction, bool buffered, int? commandTimeout, CommandType? commandType
M
mgravell 已提交
792
#else
793
this IDbConnection cnn, string sql, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null
M
mgravell 已提交
794
#endif
795
)
S
Sam Saffron 已提交
796
        {
S
Sam Saffron 已提交
797
            var data = QueryInternal<T>(cnn, sql, param as object, transaction, commandTimeout, commandType);
S
Sam Saffron 已提交
798
            return buffered ? data.ToList() : data;
799 800
        }

M
mgravell 已提交
801 802 803
        /// <summary>
        /// Execute a command that returns multiple result sets, and access each in turn
        /// </summary>
M
mgravell 已提交
804
        public static GridReader QueryMultiple(
805 806
#if CSHARP30
this IDbConnection cnn, string sql, object param, IDbTransaction transaction, int? commandTimeout, CommandType? commandType
M
mgravell 已提交
807
#else
808
            this IDbConnection cnn, string sql, dynamic param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null
M
mgravell 已提交
809
#endif
810
)
M
mgravell 已提交
811
        {
812
            Identity identity = new Identity(sql, commandType, cnn, typeof(GridReader), (object)param == null ? null : ((object)param).GetType(), null);
813
            CacheInfo info = GetCacheInfo(identity);
M
mgravell 已提交
814 815 816

            IDbCommand cmd = null;
            IDataReader reader = null;
817
            bool wasClosed = cnn.State == ConnectionState.Closed;
M
mgravell 已提交
818 819
            try
            {
820
                if (wasClosed) cnn.Open();
821
                cmd = SetupCommand(cnn, transaction, sql, info.ParamReader, (object)param, commandTimeout, commandType);
822
                reader = cmd.ExecuteReader(wasClosed ? CommandBehavior.CloseConnection : CommandBehavior.Default);
823

824
                var result = new GridReader(cmd, reader, identity);
825
                wasClosed = false; // *if* the connection was closed and we got this far, then we now have a reader
826 827 828 829
                // with the CloseConnection flag, so the reader will deal with the connection; we
                // still need something in the "finally" to ensure that broken SQL still results
                // in the connection closing itself
                return result;
M
mgravell 已提交
830 831 832
            }
            catch
            {
833 834 835
                if (reader != null)
                {
                    if (!reader.IsClosed) try { cmd.Cancel(); }
836
                        catch { /* don't spoil the existing exception */ }
837 838
                    reader.Dispose();
                }
M
mgravell 已提交
839
                if (cmd != null) cmd.Dispose();
840
                if (wasClosed) cnn.Close();
M
mgravell 已提交
841 842 843 844
                throw;
            }
        }

845
        /// <summary>
846
        /// Return a typed list of objects, reader is closed after the call
847
        /// </summary>
M
mgravell 已提交
848
        private static IEnumerable<T> QueryInternal<T>(this IDbConnection cnn, string sql, object param, IDbTransaction transaction, int? commandTimeout, CommandType? commandType)
849
        {
850
            var identity = new Identity(sql, commandType, cnn, typeof(T), param == null ? null : param.GetType(), null);
851
            var info = GetCacheInfo(identity);
S
Sam Saffron 已提交
852

853 854 855 856 857
            IDbCommand cmd = null;
            IDataReader reader = null;

            bool wasClosed = cnn.State == ConnectionState.Closed;
            try
S
Sam Saffron 已提交
858
            {
859
                cmd = SetupCommand(cnn, transaction, sql, info.ParamReader, param, commandTimeout, commandType);
860

861 862 863
                if (wasClosed) cnn.Open();
                reader = cmd.ExecuteReader(wasClosed ? CommandBehavior.CloseConnection : CommandBehavior.Default);
                wasClosed = false; // *if* the connection was closed and we got this far, then we now have a reader
864 865 866
                // with the CloseConnection flag, so the reader will deal with the connection; we
                // still need something in the "finally" to ensure that broken SQL still results
                // in the connection closing itself
867 868 869
                var tuple = info.Deserializer;
                int hash = GetColumnHash(reader);
                if (tuple.Func == null || tuple.Hash != hash)
870
                {
871 872 873
                    tuple = info.Deserializer = new DeserializerState(hash, GetDeserializer(typeof(T), reader, 0, -1, false));
                    SetQueryCache(identity, info);
                }
S
Sam Saffron 已提交
874

875
                var func = tuple.Func;
876

877 878 879
                while (reader.Read())
                {
                    yield return (T)func(reader);
880
                }
881 882 883 884
                // happy path; close the reader cleanly - no
                // need for "Cancel" etc
                reader.Dispose();
                reader = null;
885 886 887 888
            }
            finally
            {
                if (reader != null)
889
                {
890
                    if (!reader.IsClosed) try { cmd.Cancel(); }
891
                        catch { /* don't spoil the existing exception */ }
892
                    reader.Dispose();
893
                }
894 895
                if (wasClosed) cnn.Close();
                if (cmd != null) cmd.Dispose();
S
Sam Saffron 已提交
896
            }
S
Sam Saffron 已提交
897
        }
898

S
Sam Saffron 已提交
899
        /// <summary>
S
Sam Saffron 已提交
900
        /// Maps a query to objects
S
Sam Saffron 已提交
901
        /// </summary>
S
Sam Saffron 已提交
902 903 904
        /// <typeparam name="TFirst">The first type in the recordset</typeparam>
        /// <typeparam name="TSecond">The second type in the recordset</typeparam>
        /// <typeparam name="TReturn">The return type</typeparam>
S
Sam Saffron 已提交
905 906 907 908 909
        /// <param name="cnn"></param>
        /// <param name="sql"></param>
        /// <param name="map"></param>
        /// <param name="param"></param>
        /// <param name="transaction"></param>
910
        /// <param name="buffered"></param>
S
Sam Saffron 已提交
911
        /// <param name="splitOn">The Field we should split and read the second object from (default: id)</param>
912
        /// <param name="commandTimeout">Number of seconds before command execution timeout</param>
S
Sam Saffron 已提交
913
        /// <param name="commandType">Is it a stored proc or a batch?</param>
S
Sam Saffron 已提交
914
        /// <returns></returns>
M
mgravell 已提交
915
        public static IEnumerable<TReturn> Query<TFirst, TSecond, TReturn>(
916 917
#if CSHARP30
this IDbConnection cnn, string sql, Func<TFirst, TSecond, TReturn> map, object param, IDbTransaction transaction, bool buffered, string splitOn, int? commandTimeout, CommandType? commandType
M
mgravell 已提交
918
#else
919
this IDbConnection cnn, string sql, Func<TFirst, TSecond, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null
M
mgravell 已提交
920
#endif
921
)
S
Sam Saffron 已提交
922
        {
923
            return MultiMap<TFirst, TSecond, DontMap, DontMap, DontMap, DontMap, DontMap, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
S
Sam Saffron 已提交
924 925
        }

S
Sam Saffron 已提交
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
        /// <summary>
        /// Maps a query to objects
        /// </summary>
        /// <typeparam name="TFirst"></typeparam>
        /// <typeparam name="TSecond"></typeparam>
        /// <typeparam name="TThird"></typeparam>
        /// <typeparam name="TReturn"></typeparam>
        /// <param name="cnn"></param>
        /// <param name="sql"></param>
        /// <param name="map"></param>
        /// <param name="param"></param>
        /// <param name="transaction"></param>
        /// <param name="buffered"></param>
        /// <param name="splitOn">The Field we should split and read the second object from (default: id)</param>
        /// <param name="commandTimeout">Number of seconds before command execution timeout</param>
        /// <param name="commandType"></param>
        /// <returns></returns>
M
mgravell 已提交
943 944
        public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TReturn>(
#if CSHARP30
945
this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TReturn> map, object param, IDbTransaction transaction, bool buffered, string splitOn, int? commandTimeout, CommandType? commandType
M
mgravell 已提交
946
#else
947
this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null
M
mgravell 已提交
948
#endif
949
)
S
Sam Saffron 已提交
950
        {
951
            return MultiMap<TFirst, TSecond, TThird, DontMap, DontMap, DontMap, DontMap, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
S
Sam Saffron 已提交
952 953
        }

S
Sam Saffron 已提交
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
        /// <summary>
        /// Perform a multi mapping query with 4 input parameters
        /// </summary>
        /// <typeparam name="TFirst"></typeparam>
        /// <typeparam name="TSecond"></typeparam>
        /// <typeparam name="TThird"></typeparam>
        /// <typeparam name="TFourth"></typeparam>
        /// <typeparam name="TReturn"></typeparam>
        /// <param name="cnn"></param>
        /// <param name="sql"></param>
        /// <param name="map"></param>
        /// <param name="param"></param>
        /// <param name="transaction"></param>
        /// <param name="buffered"></param>
        /// <param name="splitOn"></param>
        /// <param name="commandTimeout"></param>
        /// <param name="commandType"></param>
        /// <returns></returns>
M
mgravell 已提交
972 973
        public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TReturn>(
#if CSHARP30
974
this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TReturn> map, object param, IDbTransaction transaction, bool buffered, string splitOn, int? commandTimeout, CommandType? commandType
M
mgravell 已提交
975
#else
976
this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null
M
mgravell 已提交
977
#endif
978
)
S
Sam Saffron 已提交
979
        {
980
            return MultiMap<TFirst, TSecond, TThird, TFourth, DontMap, DontMap, DontMap, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
S
Sam Saffron 已提交
981
        }
982

M
mgravell 已提交
983
#if !CSHARP30
S
Sam Saffron 已提交
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
        /// <summary>
        /// Perform a multi mapping query with 5 input parameters
        /// </summary>
        /// <typeparam name="TFirst"></typeparam>
        /// <typeparam name="TSecond"></typeparam>
        /// <typeparam name="TThird"></typeparam>
        /// <typeparam name="TFourth"></typeparam>
        /// <typeparam name="TFifth"></typeparam>
        /// <typeparam name="TReturn"></typeparam>
        /// <param name="cnn"></param>
        /// <param name="sql"></param>
        /// <param name="map"></param>
        /// <param name="param"></param>
        /// <param name="transaction"></param>
        /// <param name="buffered"></param>
        /// <param name="splitOn"></param>
        /// <param name="commandTimeout"></param>
        /// <param name="commandType"></param>
        /// <returns></returns>
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
        public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(
            this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null
)
        {
            return MultiMap<TFirst, TSecond, TThird, TFourth, TFifth, DontMap, DontMap, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
        }

        /// <summary>
        /// Perform a multi mapping query with 6 input parameters
        /// </summary>
        /// <typeparam name="TFirst"></typeparam>
        /// <typeparam name="TSecond"></typeparam>
        /// <typeparam name="TThird"></typeparam>
        /// <typeparam name="TFourth"></typeparam>
        /// <typeparam name="TFifth"></typeparam>
        /// <typeparam name="TSixth"></typeparam>
        /// <typeparam name="TReturn"></typeparam>
        /// <param name="cnn"></param>
        /// <param name="sql"></param>
        /// <param name="map"></param>
        /// <param name="param"></param>
        /// <param name="transaction"></param>
        /// <param name="buffered"></param>
        /// <param name="splitOn"></param>
        /// <param name="commandTimeout"></param>
        /// <param name="commandType"></param>
        /// <returns></returns>
        public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn>(
            this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null
)
S
Sam Saffron 已提交
1033
        {
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
            return MultiMap<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, DontMap, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
        }


        /// <summary>
        /// Perform a multi mapping query with 7 input parameters
        /// </summary>
        /// <typeparam name="TFirst"></typeparam>
        /// <typeparam name="TSecond"></typeparam>
        /// <typeparam name="TThird"></typeparam>
        /// <typeparam name="TFourth"></typeparam>
        /// <typeparam name="TFifth"></typeparam>
        /// <typeparam name="TSixth"></typeparam>
        /// <typeparam name="TSeventh"></typeparam>
        /// <typeparam name="TReturn"></typeparam>
        /// <param name="cnn"></param>
        /// <param name="sql"></param>
        /// <param name="map"></param>
        /// <param name="param"></param>
        /// <param name="transaction"></param>
        /// <param name="buffered"></param>
        /// <param name="splitOn"></param>
        /// <param name="commandTimeout"></param>
        /// <param name="commandType"></param>
        /// <returns></returns>
        public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null)
        {
            return MultiMap<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
S
Sam Saffron 已提交
1062
        }
M
mgravell 已提交
1063
#endif
1064
        partial class DontMap { }
1065
        static IEnumerable<TReturn> MultiMap<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(
M
mgravell 已提交
1066
            this IDbConnection cnn, string sql, object map, object param, IDbTransaction transaction, bool buffered, string splitOn, int? commandTimeout, CommandType? commandType)
S
Sam Saffron 已提交
1067
        {
1068
            var results = MultiMapImpl<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(cnn, sql, map, param, transaction, splitOn, commandTimeout, commandType, null, null);
S
Sam Saffron 已提交
1069 1070 1071
            return buffered ? results.ToList() : results;
        }

1072

1073
        static IEnumerable<TReturn> MultiMapImpl<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(this IDbConnection cnn, string sql, object map, object param, IDbTransaction transaction, string splitOn, int? commandTimeout, CommandType? commandType, IDataReader reader, Identity identity)
S
Sam Saffron 已提交
1074
        {
1075
            identity = identity ?? new Identity(sql, commandType, cnn, typeof(TFirst), (object)param == null ? null : ((object)param).GetType(), new[] { typeof(TFirst), typeof(TSecond), typeof(TThird), typeof(TFourth), typeof(TFifth), typeof(TSixth), typeof(TSeventh) });
1076
            CacheInfo cinfo = GetCacheInfo(identity);
S
Sam Saffron 已提交
1077

1078 1079 1080
            IDbCommand ownedCommand = null;
            IDataReader ownedReader = null;

1081
            bool wasClosed = cnn != null && cnn.State == ConnectionState.Closed;
1082
            try
S
Sam Saffron 已提交
1083
            {
1084
                if (reader == null)
S
Sam Saffron 已提交
1085
                {
1086
                    ownedCommand = SetupCommand(cnn, transaction, sql, cinfo.ParamReader, (object)param, commandTimeout, commandType);
1087
                    if (wasClosed) cnn.Open();
1088 1089 1090
                    ownedReader = ownedCommand.ExecuteReader();
                    reader = ownedReader;
                }
1091
                DeserializerState deserializer = default(DeserializerState);
M
mgravell 已提交
1092
                Func<IDataReader, object>[] otherDeserializers = null;
S
Sam Saffron 已提交
1093

1094 1095 1096
                int hash = GetColumnHash(reader);
                if ((deserializer = cinfo.Deserializer).Func == null || (otherDeserializers = cinfo.OtherDeserializers) == null || hash != deserializer.Hash)
                {
1097
                    var deserializers = GenerateDeserializers(new Type[] { typeof(TFirst), typeof(TSecond), typeof(TThird), typeof(TFourth), typeof(TFifth), typeof(TSixth), typeof(TSeventh) }, splitOn, reader);
1098
                    deserializer = cinfo.Deserializer = new DeserializerState(hash, deserializers[0]);
S
Sam Saffron 已提交
1099 1100 1101
                    otherDeserializers = cinfo.OtherDeserializers = deserializers.Skip(1).ToArray();
                    SetQueryCache(identity, cinfo);
                }
S
Sam Saffron 已提交
1102

1103
                Func<IDataReader, TReturn> mapIt = GenerateMapper<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(deserializer.Func, otherDeserializers, map);
S
Sam Saffron 已提交
1104

S
Sam Saffron 已提交
1105 1106 1107
                if (mapIt != null)
                {
                    while (reader.Read())
1108
                    {
1109
                        yield return mapIt(reader);
1110
                    }
S
Sam Saffron 已提交
1111 1112 1113 1114 1115 1116 1117
                }
            }
            finally
            {
                try
                {
                    if (ownedReader != null)
1118
                    {
S
Sam Saffron 已提交
1119
                        ownedReader.Dispose();
1120
                    }
S
Sam Saffron 已提交
1121 1122 1123 1124
                }
                finally
                {
                    if (ownedCommand != null)
1125
                    {
S
Sam Saffron 已提交
1126
                        ownedCommand.Dispose();
1127
                    }
1128
                    if (wasClosed) cnn.Close();
1129
                }
S
Sam Saffron 已提交
1130 1131
            }
        }
1132

1133
        private static Func<IDataReader, TReturn> GenerateMapper<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(Func<IDataReader, object> deserializer, Func<IDataReader, object>[] otherDeserializers, object map)
S
Sam Saffron 已提交
1134
        {
1135
            switch (otherDeserializers.Length)
M
mgravell 已提交
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
            {
                case 1:
                    return r => ((Func<TFirst, TSecond, TReturn>)map)((TFirst)deserializer(r), (TSecond)otherDeserializers[0](r));
                case 2:
                    return r => ((Func<TFirst, TSecond, TThird, TReturn>)map)((TFirst)deserializer(r), (TSecond)otherDeserializers[0](r), (TThird)otherDeserializers[1](r));
                case 3:
                    return r => ((Func<TFirst, TSecond, TThird, TFourth, TReturn>)map)((TFirst)deserializer(r), (TSecond)otherDeserializers[0](r), (TThird)otherDeserializers[1](r), (TFourth)otherDeserializers[2](r));
#if !CSHARP30
                case 4:
                    return r => ((Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>)map)((TFirst)deserializer(r), (TSecond)otherDeserializers[0](r), (TThird)otherDeserializers[1](r), (TFourth)otherDeserializers[2](r), (TFifth)otherDeserializers[3](r));
1146 1147 1148 1149
                case 5:
                    return r => ((Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn>)map)((TFirst)deserializer(r), (TSecond)otherDeserializers[0](r), (TThird)otherDeserializers[1](r), (TFourth)otherDeserializers[2](r), (TFifth)otherDeserializers[3](r), (TSixth)otherDeserializers[4](r));
                case 6:
                    return r => ((Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>)map)((TFirst)deserializer(r), (TSecond)otherDeserializers[0](r), (TThird)otherDeserializers[1](r), (TFourth)otherDeserializers[2](r), (TFifth)otherDeserializers[3](r), (TSixth)otherDeserializers[4](r), (TSeventh)otherDeserializers[5](r));
M
mgravell 已提交
1150
#endif
M
mgravell 已提交
1151 1152
                default:
                    throw new NotSupportedException();
S
Sam Saffron 已提交
1153 1154 1155
            }
        }

M
mgravell 已提交
1156
        private static Func<IDataReader, object>[] GenerateDeserializers(Type[] types, string splitOn, IDataReader reader)
S
Sam Saffron 已提交
1157 1158 1159 1160 1161 1162 1163
        {
            int current = 0;
            var splits = splitOn.Split(',').ToArray();
            var splitIndex = 0;

            Func<Type, int> nextSplit = type =>
            {
1164
                var currentSplit = splits[splitIndex].Trim();
S
Sam Saffron 已提交
1165
                if (splits.Length > splitIndex + 1)
1166
                {
S
Sam Saffron 已提交
1167 1168 1169 1170 1171 1172 1173 1174
                    splitIndex++;
                }

                bool skipFirst = false;
                int startingPos = current + 1;
                // if our current type has the split, skip the first time you see it. 
                if (type != typeof(Object))
                {
1175 1176
                    var props = DefaultTypeMap.GetSettableProps(type);
                    var fields = DefaultTypeMap.GetSettableFields(type);
S
Sam Saffron 已提交
1177 1178

                    foreach (var name in props.Select(p => p.Name).Concat(fields.Select(f => f.Name)))
1179
                    {
S
Sam Saffron 已提交
1180
                        if (string.Equals(name, currentSplit, StringComparison.OrdinalIgnoreCase))
1181
                        {
S
Sam Saffron 已提交
1182 1183 1184
                            skipFirst = true;
                            startingPos = current;
                            break;
1185 1186
                        }
                    }
S
Sam Saffron 已提交
1187

1188
                }
S
Sam Saffron 已提交
1189 1190 1191

                int pos;
                for (pos = startingPos; pos < reader.FieldCount; pos++)
1192
                {
S
Sam Saffron 已提交
1193 1194
                    // some people like ID some id ... assuming case insensitive splits for now
                    if (splitOn == "*")
1195
                    {
S
Sam Saffron 已提交
1196
                        break;
1197
                    }
S
Sam Saffron 已提交
1198
                    if (string.Equals(reader.GetName(pos), currentSplit, StringComparison.OrdinalIgnoreCase))
1199
                    {
S
Sam Saffron 已提交
1200 1201 1202 1203 1204 1205 1206 1207
                        if (skipFirst)
                        {
                            skipFirst = false;
                        }
                        else
                        {
                            break;
                        }
1208
                    }
S
Sam Saffron 已提交
1209
                }
S
Sam Saffron 已提交
1210 1211 1212 1213
                current = pos;
                return pos;
            };

M
mgravell 已提交
1214
            var deserializers = new List<Func<IDataReader, object>>();
S
Sam Saffron 已提交
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
            int split = 0;
            bool first = true;
            foreach (var type in types)
            {
                if (type != typeof(DontMap))
                {
                    int next = nextSplit(type);
                    deserializers.Add(GetDeserializer(type, reader, split, next - split, /* returnNullIfFirstMissing: */ !first));
                    first = false;
                    split = next;
                }
S
Sam Saffron 已提交
1226
            }
S
Sam Saffron 已提交
1227 1228

            return deserializers.ToArray();
1229 1230
        }

1231
        private static CacheInfo GetCacheInfo(Identity identity)
S
Sam Saffron 已提交
1232 1233
        {
            CacheInfo info;
M
mgravell 已提交
1234
            if (!TryGetQueryCache(identity, out info))
S
Sam Saffron 已提交
1235 1236
            {
                info = new CacheInfo();
1237
                if (identity.parametersType != null)
S
Sam Saffron 已提交
1238
                {
1239
                    if (typeof(IDynamicParameters).IsAssignableFrom(identity.parametersType))
S
Sam Saffron 已提交
1240
                    {
1241
                        info.ParamReader = (cmd, obj) => { (obj as IDynamicParameters).AddParameters(cmd, identity); };
S
Sam Saffron 已提交
1242
                    }
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
#if !CSHARP30
                    else if (typeof(IEnumerable<KeyValuePair<string, object>>).IsAssignableFrom(identity.parametersType) && typeof(System.Dynamic.IDynamicMetaObjectProvider).IsAssignableFrom(identity.parametersType))
                    {
                        info.ParamReader = (cmd, obj) =>
                        {
                            IDynamicParameters mapped = new DynamicParameters(obj);
                            mapped.AddParameters(cmd, identity);
                        };
                    }
#endif
S
Sam Saffron 已提交
1253 1254
                    else
                    {
1255
                        info.ParamReader = CreateParamInfoGenerator(identity, false, true);
S
Sam Saffron 已提交
1256
                    }
1257
                }
1258
                SetQueryCache(identity, info);
1259
            }
S
Sam Saffron 已提交
1260
            return info;
1261 1262
        }

M
mgravell 已提交
1263
        private static Func<IDataReader, object> GetDeserializer(Type type, IDataReader reader, int startBound, int length, bool returnNullIfFirstMissing)
S
Sam Saffron 已提交
1264
        {
M
mgravell 已提交
1265
#if !CSHARP30
S
Sam Saffron 已提交
1266
            // dynamic is passed in as Object ... by c# design
M
mgravell 已提交
1267
            if (type == typeof(object)
1268
                || type == typeof(DapperRow))
S
Sam Saffron 已提交
1269
            {
1270
                return GetDapperRowDeserializer(reader, startBound, length, returnNullIfFirstMissing);
S
Sam Saffron 已提交
1271
            }
1272
#else
1273
            if (type.IsAssignableFrom(typeof(Dictionary<string, object>)))
1274 1275 1276
            {
                return GetDictionaryDeserializer(reader, startBound, length, returnNullIfFirstMissing);
            }
M
mgravell 已提交
1277
#endif
1278 1279 1280
            Type underlyingType = null;
            if (!(typeMap.ContainsKey(type) || type.IsEnum || type.FullName == LinqBinary ||
                (type.IsValueType && (underlyingType = Nullable.GetUnderlyingType(type)) != null && underlyingType.IsEnum)))
1281
            {
S
Sam Saffron 已提交
1282
                return GetTypeDeserializer(type, reader, startBound, length, returnNullIfFirstMissing);
1283
            }
1284
            return GetStructDeserializer(type, underlyingType ?? type, startBound);
S
Sam Saffron 已提交
1285

1286
        }
1287

M
mgravell 已提交
1288
#if !CSHARP30
M
Marc Gravell 已提交
1289
        private sealed partial class DapperTable
S
Sam Saffron 已提交
1290
        {
1291 1292
            string[] fieldNames;
            readonly Dictionary<string, int> fieldNameLookup;
S
Sam Saffron 已提交
1293

1294 1295 1296
            internal string[] FieldNames { get { return fieldNames; } }

            public DapperTable(string[] fieldNames)
S
Sam Saffron 已提交
1297
            {
1298 1299 1300 1301 1302 1303 1304 1305
                if (fieldNames == null) throw new ArgumentNullException("fieldNames");
                this.fieldNames = fieldNames;

                fieldNameLookup = new Dictionary<string, int>(fieldNames.Length, StringComparer.Ordinal);
                // if there are dups, we want the **first** key to be the "winner" - so iterate backwards
                for (int i = fieldNames.Length - 1; i >= 0; i--)
                {
                    string key = fieldNames[i];
1306
                    if (key != null) fieldNameLookup[key] = i;
1307
                }
S
Sam Saffron 已提交
1308 1309
            }

1310
            internal int IndexOfName(string name)
S
Sam Saffron 已提交
1311
            {
1312 1313 1314 1315 1316 1317 1318 1319 1320
                int result;
                return (name != null && fieldNameLookup.TryGetValue(name, out result)) ? result : -1;
            }
            internal int AddField(string name)
            {
                if (name == null) throw new ArgumentNullException("name");
                if (fieldNameLookup.ContainsKey(name)) throw new InvalidOperationException("Field already exists: " + name);
                int oldLen = fieldNames.Length;
                Array.Resize(ref fieldNames, oldLen + 1); // yes, this is sub-optimal, but this is not the expected common case
1321
                fieldNames[oldLen] = name;
1322 1323
                fieldNameLookup[name] = oldLen;
                return oldLen;
1324 1325
            }

1326 1327

            internal bool FieldExists(string key)
1328
            {
1329
                return key != null && fieldNameLookup.ContainsKey(key);
1330 1331
            }

1332 1333 1334 1335 1336 1337
            public int FieldCount { get { return fieldNames.Length; } }
        }

        sealed partial class DapperRowMetaObject : System.Dynamic.DynamicMetaObject
        {
            static readonly MethodInfo getValueMethod = typeof(IDictionary<string, object>).GetProperty("Item").GetGetMethod();
1338
            static readonly MethodInfo setValueMethod = typeof(DapperRow).GetMethod("SetValue", new Type[] { typeof(string), typeof(object) });
1339 1340 1341 1342 1343 1344

            public DapperRowMetaObject(
                System.Linq.Expressions.Expression expression,
                System.Dynamic.BindingRestrictions restrictions
                )
                : base(expression, restrictions)
1345 1346 1347
            {
            }

1348 1349 1350 1351 1352 1353 1354 1355
            public DapperRowMetaObject(
                System.Linq.Expressions.Expression expression,
                System.Dynamic.BindingRestrictions restrictions,
                object value
                )
                : base(expression, restrictions, value)
            {
            }
1356

1357 1358 1359 1360
            System.Dynamic.DynamicMetaObject CallMethod(
                MethodInfo method,
                System.Linq.Expressions.Expression[] parameters
                )
1361
            {
1362 1363 1364 1365 1366 1367 1368 1369
                var callMethod = new System.Dynamic.DynamicMetaObject(
                    System.Linq.Expressions.Expression.Call(
                        System.Linq.Expressions.Expression.Convert(Expression, LimitType),
                        method,
                        parameters),
                    System.Dynamic.BindingRestrictions.GetTypeRestriction(Expression, LimitType)
                    );
                return callMethod;
1370 1371
            }

1372
            public override System.Dynamic.DynamicMetaObject BindGetMember(System.Dynamic.GetMemberBinder binder)
1373
            {
1374 1375 1376 1377 1378 1379 1380 1381
                var parameters = new System.Linq.Expressions.Expression[]
                                     {
                                         System.Linq.Expressions.Expression.Constant(binder.Name)
                                     };

                var callMethod = CallMethod(getValueMethod, parameters);

                return callMethod;
1382 1383
            }

1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
            // Needed for Visual basic dynamic support
            public override System.Dynamic.DynamicMetaObject BindInvokeMember(System.Dynamic.InvokeMemberBinder binder, System.Dynamic.DynamicMetaObject[] args)
            {
                var parameters = new System.Linq.Expressions.Expression[]
                                     {
                                         System.Linq.Expressions.Expression.Constant(binder.Name)
                                     };

                var callMethod = CallMethod(getValueMethod, parameters);

                return callMethod;
            }

1397
            public override System.Dynamic.DynamicMetaObject BindSetMember(System.Dynamic.SetMemberBinder binder, System.Dynamic.DynamicMetaObject value)
1398
            {
1399 1400 1401 1402 1403 1404 1405 1406 1407
                var parameters = new System.Linq.Expressions.Expression[]
                                     {
                                         System.Linq.Expressions.Expression.Constant(binder.Name),
                                         value.Expression,
                                     };

                var callMethod = CallMethod(setValueMethod, parameters);

                return callMethod;
1408
            }
1409
        }
1410

M
Marc Gravell 已提交
1411
        private sealed partial class DapperRow
1412 1413 1414 1415 1416 1417 1418
            : System.Dynamic.IDynamicMetaObjectProvider
            , IDictionary<string, object>
        {
            readonly DapperTable table;
            object[] values;

            public DapperRow(DapperTable table, object[] values)
1419
            {
1420 1421 1422 1423
                if (table == null) throw new ArgumentNullException("table");
                if (values == null) throw new ArgumentNullException("values");
                this.table = table;
                this.values = values;
1424
            }
1425 1426 1427 1428 1429 1430
            private sealed class DeadValue
            {
                public static readonly DeadValue Default = new DeadValue();
                private DeadValue() { }
            }
            int ICollection<KeyValuePair<string, object>>.Count
1431
            {
1432 1433 1434 1435 1436 1437 1438 1439 1440
                get
                {
                    int count = 0;
                    for (int i = 0; i < values.Length; i++)
                    {
                        if (!(values[i] is DeadValue)) count++;
                    }
                    return count;
                }
1441 1442
            }

1443
            public bool TryGetValue(string name, out object value)
1444
            {
1445 1446 1447 1448 1449 1450 1451 1452
                var index = table.IndexOfName(name);
                if (index < 0)
                { // doesn't exist
                    value = null;
                    return false;
                }
                // exists, **even if** we don't have a value; consider table rows heterogeneous
                value = index < values.Length ? values[index] : null;
1453 1454 1455 1456 1457
                if (value is DeadValue)
                { // pretend it isn't here
                    value = null;
                    return false;
                }
1458
                return true;
1459 1460
            }

1461 1462 1463 1464
            public override string ToString()
            {
                var sb = new StringBuilder("{DapperRow");
                foreach (var kv in this)
1465
                {
1466
                    var value = kv.Value;
1467
                    sb.Append(", ").Append(kv.Key);
1468 1469
                    if (value != null)
                    {
1470
                        sb.Append(" = '").Append(kv.Value).Append('\'');
1471 1472 1473 1474 1475
                    }
                    else
                    {
                        sb.Append(" = NULL");
                    }
1476
                }
1477

1478
                return sb.Append('}').ToString();
1479 1480
            }

1481 1482
            System.Dynamic.DynamicMetaObject System.Dynamic.IDynamicMetaObjectProvider.GetMetaObject(
                System.Linq.Expressions.Expression parameter)
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
            {
                return new DapperRowMetaObject(parameter, System.Dynamic.BindingRestrictions.Empty, this);
            }

            public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
            {
                var names = table.FieldNames;
                for (var i = 0; i < names.Length; i++)
                {
                    object value = i < values.Length ? values[i] : null;
1493 1494 1495 1496
                    if (!(value is DeadValue))
                    {
                        yield return new KeyValuePair<string, object>(names[i], value);
                    }
1497 1498 1499 1500 1501 1502 1503
                }
            }

            IEnumerator IEnumerable.GetEnumerator()
            {
                return GetEnumerator();
            }
1504

1505
        #region Implementation of ICollection<KeyValuePair<string,object>>
1506 1507 1508

            void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item)
            {
1509 1510
                IDictionary<string, object> dic = this;
                dic.Add(item.Key, item.Value);
1511 1512 1513
            }

            void ICollection<KeyValuePair<string, object>>.Clear()
1514
            { // removes values for **this row**, but doesn't change the fundamental table
1515 1516
                for (int i = 0; i < values.Length; i++)
                    values[i] = DeadValue.Default;
1517 1518 1519 1520
            }

            bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item)
            {
1521 1522
                object value;
                return TryGetValue(item.Key, out value) && Equals(value, item.Value);
1523 1524 1525 1526
            }

            void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
            {
1527 1528 1529 1530
                foreach (var kv in this)
                {
                    array[arrayIndex++] = kv; // if they didn't leave enough space; not our fault
                }
1531 1532
            }

1533
            bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item)
1534
            {
1535 1536
                IDictionary<string, object> dic = this;
                return dic.Remove(item.Key);
1537 1538 1539 1540
            }

            bool ICollection<KeyValuePair<string, object>>.IsReadOnly
            {
1541
                get { return false; }
1542 1543
            }

1544 1545
            #endregion

1546
        #region Implementation of IDictionary<string,object>
1547 1548

            bool IDictionary<string, object>.ContainsKey(string key)
1549
            {
1550 1551 1552
                int index = table.IndexOfName(key);
                if (index < 0 || index >= values.Length || values[index] is DeadValue) return false;
                return true;
1553 1554
            }

1555 1556
            void IDictionary<string, object>.Add(string key, object value)
            {
1557
                SetValue(key, value, true);
1558
            }
1559

1560
            bool IDictionary<string, object>.Remove(string key)
1561
            {
1562
                int index = table.IndexOfName(key);
1563 1564 1565
                if (index < 0 || index >= values.Length || values[index] is DeadValue) return false;
                values[index] = DeadValue.Default;
                return true;
1566 1567
            }

1568 1569 1570
            object IDictionary<string, object>.this[string key]
            {
                get { object val; TryGetValue(key, out val); return val; }
1571
                set { SetValue(key, value, false); }
1572
            }
1573

1574
            public object SetValue(string key, object value)
1575 1576 1577 1578
            {
                return SetValue(key, value, false);
            }
            private object SetValue(string key, object value, bool isAdd)
1579 1580 1581 1582 1583 1584 1585
            {
                if (key == null) throw new ArgumentNullException("key");
                int index = table.IndexOfName(key);
                if (index < 0)
                {
                    index = table.AddField(key);
                }
1586 1587 1588 1589 1590 1591 1592 1593 1594
                else if (isAdd && index < values.Length && !(values[index] is DeadValue))
                {
                    // then semantically, this value already exists
                    throw new ArgumentException("An item with the same key has already been added", "key");
                }
                int oldLength = values.Length;
                if (oldLength <= index)
                {
                    // we'll assume they're doing lots of things, and
1595 1596
                    // grow it to the full width of the table
                    Array.Resize(ref values, table.FieldCount);
1597 1598 1599 1600
                    for (int i = oldLength; i < values.Length; i++)
                    {
                        values[i] = DeadValue.Default;
                    }
1601
                }
1602
                return values[index] = value;
1603
            }
1604

1605 1606 1607 1608
            ICollection<string> IDictionary<string, object>.Keys
            {
                get { return this.Select(kv => kv.Key).ToArray(); }
            }
1609

1610
            ICollection<object> IDictionary<string, object>.Values
1611
            {
1612
                get { return this.Select(kv => kv.Value).ToArray(); }
1613 1614 1615
            }

            #endregion
S
Sam Saffron 已提交
1616
        }
1617
#endif
1618
        private const string MultiMapSplitExceptionMessage = "When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id";
1619
#if !CSHARP30
1620 1621 1622 1623 1624 1625 1626
        internal static Func<IDataReader, object> GetDapperRowDeserializer(IDataRecord reader, int startBound, int length, bool returnNullIfFirstMissing)
        {
            var fieldCount = reader.FieldCount;
            if (length == -1)
            {
                length = fieldCount - startBound;
            }
1627

1628 1629
            if (fieldCount <= startBound)
            {
1630
                throw new ArgumentException(MultiMapSplitExceptionMessage, "splitOn");
1631 1632
            }

1633
            var effectiveFieldCount = Math.Min(fieldCount - startBound, length);
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644

            DapperTable table = null;

            return
                r =>
                {
                    if (table == null)
                    {
                        string[] names = new string[effectiveFieldCount];
                        for (int i = 0; i < effectiveFieldCount; i++)
                        {
1645
                            names[i] = r.GetName(i + startBound);
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
                        }
                        table = new DapperTable(names);
                    }

                    var values = new object[effectiveFieldCount];

                    if (returnNullIfFirstMissing)
                    {
                        values[0] = r.GetValue(startBound);
                        if (values[0] is DBNull)
                        {
                            return null;
                        }
                    }

                    if (startBound == 0)
                    {
                        r.GetValues(values);
M
Marc Gravell 已提交
1664 1665
                        for (int i = 0; i < values.Length; i++)
                            if (values[i] is DBNull) values[i] = null;
1666 1667 1668 1669 1670 1671
                    }
                    else
                    {
                        var begin = returnNullIfFirstMissing ? 1 : 0;
                        for (var iter = begin; iter < effectiveFieldCount; ++iter)
                        {
M
Marc Gravell 已提交
1672 1673
                            object obj = r.GetValue(iter + startBound);
                            values[iter] = obj is DBNull ? null : obj;
1674 1675 1676 1677 1678 1679 1680
                        }
                    }
                    return new DapperRow(table, values);
                };
        }
#else
        internal static Func<IDataReader, object> GetDictionaryDeserializer(IDataRecord reader, int startBound, int length, bool returnNullIfFirstMissing)
S
Sam Saffron 已提交
1681
        {
1682
            var fieldCount = reader.FieldCount;
1683 1684
            if (length == -1)
            {
1685 1686 1687 1688 1689
                length = fieldCount - startBound;
            }

            if (fieldCount <= startBound)
            {
1690
                throw new ArgumentException(MultiMapSplitExceptionMessage, "splitOn");
1691 1692
            }

1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
            return
                 r =>
                 {
                     IDictionary<string, object> row = new Dictionary<string, object>(length);
                     for (var i = startBound; i < startBound + length; i++)
                     {
                         var tmp = r.GetValue(i);
                         tmp = tmp == DBNull.Value ? null : tmp;
                         row[r.GetName(i)] = tmp;
                         if (returnNullIfFirstMissing && i == startBound && tmp == null)
                         {
M
mgravell 已提交
1704
                             return null;
1705 1706
                         }
                     }
1707
                     return row;
1708
                 };
S
Sam Saffron 已提交
1709
        }
1710
#endif
S
Sam Saffron 已提交
1711 1712 1713 1714 1715
        /// <summary>
        /// Internal use only
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
M
mgravell 已提交
1716 1717 1718 1719 1720 1721 1722
        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        [Obsolete("This method is for internal usage only", false)]
        public static char ReadChar(object value)
        {
            if (value == null || value is DBNull) throw new ArgumentNullException("value");
            string s = value as string;
            if (s == null || s.Length != 1) throw new ArgumentException("A single-character was expected", "value");
1723
            return s[0];
M
mgravell 已提交
1724
        }
S
Sam Saffron 已提交
1725 1726 1727 1728

        /// <summary>
        /// Internal use only
        /// </summary>
M
mgravell 已提交
1729 1730 1731 1732 1733 1734 1735
        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        [Obsolete("This method is for internal usage only", false)]
        public static char? ReadNullableChar(object value)
        {
            if (value == null || value is DBNull) return null;
            string s = value as string;
            if (s == null || s.Length != 1) throw new ArgumentException("A single-character was expected", "value");
1736
            return s[0];
M
mgravell 已提交
1737
        }
1738

1739

1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
        /// <summary>
        /// Internal use only
        /// </summary>
        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        [Obsolete("This method is for internal usage only", true)]
        public static IDbDataParameter FindOrAddParameter(IDataParameterCollection parameters, IDbCommand command, string name)
        {
            IDbDataParameter result;
            if (parameters.Contains(name))
            {
                result = (IDbDataParameter)parameters[name];
            }
            else
            {
                result = command.CreateParameter();
                result.ParameterName = name;
                parameters.Add(result);
            }
            return result;
        }

S
Sam Saffron 已提交
1761 1762 1763
        /// <summary>
        /// Internal use only
        /// </summary>
1764
        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
1765
        [Obsolete("This method is for internal usage only", false)]
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
        public static void PackListParameters(IDbCommand command, string namePrefix, object value)
        {
            // initially we tried TVP, however it performs quite poorly.
            // keep in mind SQL support up to 2000 params easily in sp_executesql, needing more is rare

            var list = value as IEnumerable;
            var count = 0;

            if (list != null)
            {
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829
                if (FeatureSupport.Get(command.Connection).Arrays)
                {
                    var arrayParm = command.CreateParameter();
                    arrayParm.Value = list;
                    arrayParm.ParameterName = namePrefix;
                    command.Parameters.Add(arrayParm);
                }
                else
                {
                    bool isString = value is IEnumerable<string>;
                    bool isDbString = value is IEnumerable<DbString>;
                    foreach (var item in list)
                    {
                        count++;
                        var listParam = command.CreateParameter();
                        listParam.ParameterName = namePrefix + count;
                        listParam.Value = item ?? DBNull.Value;
                        if (isString)
                        {
                            listParam.Size = 4000;
                            if (item != null && ((string)item).Length > 4000)
                            {
                                listParam.Size = -1;
                            }
                        }
                        if (isDbString && item as DbString != null)
                        {
                            var str = item as DbString;
                            str.AddParameter(command, listParam.ParameterName);
                        }
                        else
                        {
                            command.Parameters.Add(listParam);
                        }
                    }

                    if (count == 0)
                    {
                        command.CommandText = Regex.Replace(command.CommandText, @"[?@:]" + Regex.Escape(namePrefix), "(SELECT NULL WHERE 1 = 0)");
                    }
                    else
                    {
                        command.CommandText = Regex.Replace(command.CommandText, @"[?@:]" + Regex.Escape(namePrefix), match =>
                        {
                            var grp = match.Value;
                            var sb = new StringBuilder("(").Append(grp).Append(1);
                            for (int i = 2; i <= count; i++)
                            {
                                sb.Append(',').Append(grp).Append(i);
                            }
                            return sb.Append(')').ToString();
                        });
                    }
                }
1830
            }
S
Sam Saffron 已提交
1831

1832
        }
S
Sam Saffron 已提交
1833

1834 1835
        private static IEnumerable<PropertyInfo> FilterParameters(IEnumerable<PropertyInfo> parameters, string sql)
        {
1836
            return parameters.Where(p => Regex.IsMatch(sql, @"[?@:]" + p.Name + "([^a-zA-Z0-9_]+|$)", RegexOptions.IgnoreCase | RegexOptions.Multiline));
1837
        }
S
Sam Saffron 已提交
1838

1839 1840 1841 1842

        // look for ? / @ / : *by itself*
        static readonly Regex smellsLikeOleDb = new Regex(@"(?<![a-zA-Z0-9_])[?@:](?![a-zA-Z0-9_])", RegexOptions.Compiled);
        
S
Sam Saffron 已提交
1843 1844 1845
        /// <summary>
        /// Internal use only
        /// </summary>
1846
        public static Action<IDbCommand, object> CreateParamInfoGenerator(Identity identity, bool checkForDuplicates, bool removeUnused)
S
Sam Saffron 已提交
1847
        {
1848
            Type type = identity.parametersType;
1849 1850 1851 1852 1853 1854
            
            bool filterParams = false;
            if (removeUnused && identity.commandType.GetValueOrDefault(CommandType.Text) == CommandType.Text)
            {
                filterParams = !smellsLikeOleDb.IsMatch(identity.sql);
            }
1855
            var dm = new DynamicMethod(string.Format("ParamInfo{0}", Guid.NewGuid()), null, new[] { typeof(IDbCommand), typeof(object) }, type, true);
S
Sam Saffron 已提交
1856 1857 1858 1859

            var il = dm.GetILGenerator();

            il.DeclareLocal(type); // 0
1860 1861
            bool haveInt32Arg1 = false;
            il.Emit(OpCodes.Ldarg_1); // stack is now [untyped-param]
S
Sam Saffron 已提交
1862 1863 1864
            il.Emit(OpCodes.Unbox_Any, type); // stack is now [typed-param]
            il.Emit(OpCodes.Stloc_0);// stack is now empty

1865 1866
            il.Emit(OpCodes.Ldarg_0); // stack is now [command]
            il.EmitCall(OpCodes.Callvirt, typeof(IDbCommand).GetProperty("Parameters").GetGetMethod(), null); // stack is now [parameters]
1867

1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919
            var propsArr = type.GetProperties().Where(p => p.GetIndexParameters().Length == 0).ToArray();
            var ctors = type.GetConstructors();
            ParameterInfo[] ctorParams;
            IEnumerable<PropertyInfo> props = null;
            // try to detect tuple patterns, e.g. anon-types, and use that to choose the order
            // otherwise: alphabetical
            if (ctors.Length == 1 && propsArr.Length == (ctorParams = ctors[0].GetParameters()).Length)
            {
                // check if reflection was kind enough to put everything in the right order for us
                bool ok = true;
                for (int i = 0; i < propsArr.Length; i++)
                {
                    if (!string.Equals(propsArr[i].Name, ctorParams[i].Name, StringComparison.InvariantCultureIgnoreCase))
                    {
                        ok = false;
                        break;
                    }
                }
                if(ok)
                {
                    // pre-sorted; the reflection gods have smiled upon us
                    props = propsArr;
                }
                else { // might still all be accounted for; check the hard way
                    var positionByName = new Dictionary<string,int>(StringComparer.InvariantCultureIgnoreCase);
                    foreach(var param in ctorParams)
                    {
                        positionByName[param.Name] = param.Position;
                    }
                    if (positionByName.Count == propsArr.Length)
                    {
                        int[] positions = new int[propsArr.Length];
                        ok = true;
                        for (int i = 0; i < propsArr.Length; i++)
                        {
                            int pos;
                            if (!positionByName.TryGetValue(propsArr[i].Name, out pos))
                            {
                                ok = false;
                                break;
                            }
                            positions[i] = pos;
                        }
                        if (ok)
                        {
                            Array.Sort(positions, propsArr);
                            props = propsArr;
                        }
                    }
                }
            }
            if(props == null) props = propsArr.OrderBy(x => x.Name);
1920 1921 1922 1923
            if (filterParams)
            {
                props = FilterParameters(props, identity.sql);
            }
1924

1925
            foreach (var prop in props)
S
Sam Saffron 已提交
1926
            {
1927 1928 1929
                if (filterParams)
                {
                    if (identity.sql.IndexOf("@" + prop.Name, StringComparison.InvariantCultureIgnoreCase) < 0
1930 1931
                        && identity.sql.IndexOf(":" + prop.Name, StringComparison.InvariantCultureIgnoreCase) < 0
                        && identity.sql.IndexOf("?" + prop.Name, StringComparison.InvariantCultureIgnoreCase) < 0)
1932 1933
                    { // can't see the parameter in the text (even in a comment, etc) - burn it with fire
                        continue;
1934
                    }
1935
                }
1936
                if (typeof(ICustomQueryParameter).IsAssignableFrom(prop.PropertyType))
M
mgravell 已提交
1937 1938 1939 1940
                {
                    il.Emit(OpCodes.Ldloc_0); // stack is now [parameters] [typed-param]
                    il.Emit(OpCodes.Callvirt, prop.GetGetMethod()); // stack is [parameters] [dbstring]
                    il.Emit(OpCodes.Ldarg_0); // stack is now [parameters] [dbstring] [command]
1941
                    il.Emit(OpCodes.Ldstr, prop.Name); // stack is now [parameters] [dbstring] [command] [name]
1942
                    il.EmitCall(OpCodes.Callvirt, prop.PropertyType.GetMethod("AddParameter"), null); // stack is now [parameters]
M
mgravell 已提交
1943 1944
                    continue;
                }
1945
                DbType dbType = LookupDbType(prop.PropertyType, prop.Name);
1946
                if (dbType == DynamicParameters.EnumerableMultiParameter)
1947 1948 1949
                {
                    // this actually represents special handling for list types;
                    il.Emit(OpCodes.Ldarg_0); // stack is now [parameters] [command]
1950
                    il.Emit(OpCodes.Ldstr, prop.Name); // stack is now [parameters] [command] [name]
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
                    il.Emit(OpCodes.Ldloc_0); // stack is now [parameters] [command] [name] [typed-param]
                    il.Emit(OpCodes.Callvirt, prop.GetGetMethod()); // stack is [parameters] [command] [name] [typed-value]
                    if (prop.PropertyType.IsValueType)
                    {
                        il.Emit(OpCodes.Box, prop.PropertyType); // stack is [parameters] [command] [name] [boxed-value]
                    }
                    il.EmitCall(OpCodes.Call, typeof(SqlMapper).GetMethod("PackListParameters"), null); // stack is [parameters]
                    continue;
                }
                il.Emit(OpCodes.Dup); // stack is now [parameters] [parameters]

                il.Emit(OpCodes.Ldarg_0); // stack is now [parameters] [parameters] [command]

1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
                if (checkForDuplicates)
                {
                    // need to be a little careful about adding; use a utility method
                    il.Emit(OpCodes.Ldstr, prop.Name); // stack is now [parameters] [parameters] [command] [name]
                    il.EmitCall(OpCodes.Call, typeof(SqlMapper).GetMethod("FindOrAddParameter"), null); // stack is [parameters] [parameter]
                }
                else
                {
                    // no risk of duplicates; just blindly add
                    il.EmitCall(OpCodes.Callvirt, typeof(IDbCommand).GetMethod("CreateParameter"), null);// stack is now [parameters] [parameters] [parameter]
1974

1975 1976 1977 1978
                    il.Emit(OpCodes.Dup);// stack is now [parameters] [parameters] [parameter] [parameter]
                    il.Emit(OpCodes.Ldstr, prop.Name); // stack is now [parameters] [parameters] [parameter] [parameter] [name]
                    il.EmitCall(OpCodes.Callvirt, typeof(IDataParameter).GetProperty("ParameterName").GetSetMethod(), null);// stack is now [parameters] [parameters] [parameter]
                }
1979
                if (dbType != DbType.Time) // https://connect.microsoft.com/VisualStudio/feedback/details/381934/sqlparameter-dbtype-dbtype-time-sets-the-parameter-to-sqldbtype-datetime-instead-of-sqldbtype-time
J
Jakub Konecki 已提交
1980
                {
1981 1982
                    il.Emit(OpCodes.Dup);// stack is now [parameters] [[parameters]] [parameter] [parameter]
                    EmitInt32(il, (int)dbType);// stack is now [parameters] [[parameters]] [parameter] [parameter] [db-type]
S
Sam Saffron 已提交
1983

1984
                    il.EmitCall(OpCodes.Callvirt, typeof(IDataParameter).GetProperty("DbType").GetSetMethod(), null);// stack is now [parameters] [[parameters]] [parameter]
J
Jakub Konecki 已提交
1985
                }
S
Sam Saffron 已提交
1986

1987 1988 1989
                il.Emit(OpCodes.Dup);// stack is now [parameters] [[parameters]] [parameter] [parameter]
                EmitInt32(il, (int)ParameterDirection.Input);// stack is now [parameters] [[parameters]] [parameter] [parameter] [dir]
                il.EmitCall(OpCodes.Callvirt, typeof(IDataParameter).GetProperty("Direction").GetSetMethod(), null);// stack is now [parameters] [[parameters]] [parameter]
1990

1991 1992 1993
                il.Emit(OpCodes.Dup);// stack is now [parameters] [[parameters]] [parameter] [parameter]
                il.Emit(OpCodes.Ldloc_0); // stack is now [parameters] [[parameters]] [parameter] [parameter] [typed-param]
                il.Emit(OpCodes.Callvirt, prop.GetGetMethod()); // stack is [parameters] [[parameters]] [parameter] [parameter] [typed-value]
1994
                bool checkForNull = true;
S
Sam Saffron 已提交
1995 1996
                if (prop.PropertyType.IsValueType)
                {
1997
                    il.Emit(OpCodes.Box, prop.PropertyType); // stack is [parameters] [[parameters]] [parameter] [parameter] [boxed-value]
1998 1999 2000 2001
                    if (Nullable.GetUnderlyingType(prop.PropertyType) == null)
                    {   // struct but not Nullable<T>; boxed value cannot be null
                        checkForNull = false;
                    }
S
Sam Saffron 已提交
2002
                }
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
                if (checkForNull)
                {
                    if (dbType == DbType.String && !haveInt32Arg1)
                    {
                        il.DeclareLocal(typeof(int));
                        haveInt32Arg1 = true;
                    }
                    // relative stack: [boxed value]
                    il.Emit(OpCodes.Dup);// relative stack: [boxed value] [boxed value]
                    Label notNull = il.DefineLabel();
                    Label? allDone = dbType == DbType.String ? il.DefineLabel() : (Label?)null;
                    il.Emit(OpCodes.Brtrue_S, notNull);
                    // relative stack [boxed value = null]
                    il.Emit(OpCodes.Pop); // relative stack empty
                    il.Emit(OpCodes.Ldsfld, typeof(DBNull).GetField("Value")); // relative stack [DBNull]
                    if (dbType == DbType.String)
                    {
                        EmitInt32(il, 0);
                        il.Emit(OpCodes.Stloc_1);
                    }
                    if (allDone != null) il.Emit(OpCodes.Br_S, allDone.Value);
                    il.MarkLabel(notNull);
                    if (prop.PropertyType == typeof(string))
                    {
                        il.Emit(OpCodes.Dup); // [string] [string]
                        il.EmitCall(OpCodes.Callvirt, typeof(string).GetProperty("Length").GetGetMethod(), null); // [string] [length]
                        EmitInt32(il, 4000); // [string] [length] [4000]
                        il.Emit(OpCodes.Cgt); // [string] [0 or 1]
                        Label isLong = il.DefineLabel(), lenDone = il.DefineLabel();
                        il.Emit(OpCodes.Brtrue_S, isLong);
                        EmitInt32(il, 4000); // [string] [4000]
                        il.Emit(OpCodes.Br_S, lenDone);
                        il.MarkLabel(isLong);
                        EmitInt32(il, -1); // [string] [-1]
                        il.MarkLabel(lenDone);
                        il.Emit(OpCodes.Stloc_1); // [string] 
                    }
M
mgravell 已提交
2040
                    if (prop.PropertyType.FullName == LinqBinary)
M
mgravell 已提交
2041
                    {
M
mgravell 已提交
2042
                        il.EmitCall(OpCodes.Callvirt, prop.PropertyType.GetMethod("ToArray", BindingFlags.Public | BindingFlags.Instance), null);
M
mgravell 已提交
2043
                    }
2044 2045 2046
                    if (allDone != null) il.MarkLabel(allDone.Value);
                    // relative stack [boxed value or DBNull]
                }
2047
                il.EmitCall(OpCodes.Callvirt, typeof(IDataParameter).GetProperty("Value").GetSetMethod(), null);// stack is now [parameters] [[parameters]] [parameter]
S
Sam Saffron 已提交
2048

2049 2050 2051 2052
                if (prop.PropertyType == typeof(string))
                {
                    var endOfSize = il.DefineLabel();
                    // don't set if 0
2053 2054
                    il.Emit(OpCodes.Ldloc_1); // [parameters] [[parameters]] [parameter] [size]
                    il.Emit(OpCodes.Brfalse_S, endOfSize); // [parameters] [[parameters]] [parameter]
2055

2056 2057 2058
                    il.Emit(OpCodes.Dup);// stack is now [parameters] [[parameters]] [parameter] [parameter]
                    il.Emit(OpCodes.Ldloc_1); // stack is now [parameters] [[parameters]] [parameter] [parameter] [size]
                    il.EmitCall(OpCodes.Callvirt, typeof(IDbDataParameter).GetProperty("Size").GetSetMethod(), null); // stack is now [parameters] [[parameters]] [parameter]
S
Sam Saffron 已提交
2059

2060 2061
                    il.MarkLabel(endOfSize);
                }
2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073
                if (checkForDuplicates)
                {
                    // stack is now [parameters] [parameter]
                    il.Emit(OpCodes.Pop); // don't need parameter any more
                }
                else
                {
                    // stack is now [parameters] [parameters] [parameter]
                    // blindly add
                    il.EmitCall(OpCodes.Callvirt, typeof(IList).GetMethod("Add"), null); // stack is now [parameters]
                    il.Emit(OpCodes.Pop); // IList.Add returns the new index (int); we don't care
                }
2074
            }
2075
            // stack is currently [parameters]
2076 2077 2078
            il.Emit(OpCodes.Pop); // stack is now empty
            il.Emit(OpCodes.Ret);
            return (Action<IDbCommand, object>)dm.CreateDelegate(typeof(Action<IDbCommand, object>));
S
Sam Saffron 已提交
2079 2080
        }

S
Sam Saffron 已提交
2081
        private static IDbCommand SetupCommand(IDbConnection cnn, IDbTransaction transaction, string sql, Action<IDbCommand, object> paramReader, object obj, int? commandTimeout, CommandType? commandType)
S
Sam Saffron 已提交
2082
        {
S
Sam Saffron 已提交
2083
            var cmd = cnn.CreateCommand();
M
mgravell 已提交
2084 2085
            var bindByName = GetBindByName(cmd.GetType());
            if (bindByName != null) bindByName(cmd, true);
2086 2087
            if (transaction != null)
                cmd.Transaction = transaction;
S
Sam Saffron 已提交
2088
            cmd.CommandText = sql;
2089 2090
            if (commandTimeout.HasValue)
                cmd.CommandTimeout = commandTimeout.Value;
S
Sam Saffron 已提交
2091 2092
            if (commandType.HasValue)
                cmd.CommandType = commandType.Value;
2093
            if (paramReader != null)
S
Sam Saffron 已提交
2094
            {
2095
                paramReader(cmd, obj);
S
Sam Saffron 已提交
2096 2097 2098 2099 2100
            }
            return cmd;
        }


S
typo  
Sam Saffron 已提交
2101
        private static int ExecuteCommand(IDbConnection cnn, IDbTransaction transaction, string sql, Action<IDbCommand, object> paramReader, object obj, int? commandTimeout, CommandType? commandType)
S
Sam Saffron 已提交
2102
        {
2103 2104 2105
            IDbCommand cmd = null;
            bool wasClosed = cnn.State == ConnectionState.Closed;
            try
S
Sam Saffron 已提交
2106
            {
2107 2108
                cmd = SetupCommand(cnn, transaction, sql, paramReader, obj, commandTimeout, commandType);
                if (wasClosed) cnn.Open();
S
Sam Saffron 已提交
2109 2110
                return cmd.ExecuteNonQuery();
            }
2111 2112 2113 2114 2115
            finally
            {
                if (wasClosed) cnn.Close();
                if (cmd != null) cmd.Dispose();
            }
S
Sam Saffron 已提交
2116 2117
        }

2118
        private static Func<IDataReader, object> GetStructDeserializer(Type type, Type effectiveType, int index)
S
Sam Saffron 已提交
2119
        {
M
mgravell 已提交
2120 2121
            // no point using special per-type handling here; it boils down to the same, plus not all are supported anyway (see: SqlDataReader.GetChar - not supported!)
#pragma warning disable 618
M
mgravell 已提交
2122
            if (type == typeof(char))
M
mgravell 已提交
2123
            { // this *does* need special handling, though
M
mgravell 已提交
2124
                return r => SqlMapper.ReadChar(r.GetValue(index));
M
mgravell 已提交
2125
            }
M
mgravell 已提交
2126
            if (type == typeof(char?))
M
mgravell 已提交
2127
            {
M
mgravell 已提交
2128
                return r => SqlMapper.ReadNullableChar(r.GetValue(index));
M
mgravell 已提交
2129
            }
M
mgravell 已提交
2130
            if (type.FullName == LinqBinary)
M
mgravell 已提交
2131
            {
M
mgravell 已提交
2132
                return r => Activator.CreateInstance(type, r.GetValue(index));
M
mgravell 已提交
2133
            }
M
mgravell 已提交
2134
#pragma warning restore 618
2135 2136 2137 2138 2139 2140 2141 2142 2143

            if (effectiveType.IsEnum)
            {   // assume the value is returned as the correct type (int/byte/etc), but box back to the typed enum
                return r =>
                {
                    var val = r.GetValue(index);
                    return val is DBNull ? null : Enum.ToObject(effectiveType, val);
                };
            }
2144
            return r =>
S
Sam Saffron 已提交
2145
            {
2146
                var val = r.GetValue(index);
M
mgravell 已提交
2147
                return val is DBNull ? null : val;
S
Sam Saffron 已提交
2148
            };
S
Sam Saffron 已提交
2149
        }
2150

M
mgravell 已提交
2151 2152 2153 2154 2155
        static readonly MethodInfo
                    enumParse = typeof(Enum).GetMethod("Parse", new Type[] { typeof(Type), typeof(string), typeof(bool) }),
                    getItem = typeof(IDataRecord).GetProperties(BindingFlags.Instance | BindingFlags.Public)
                        .Where(p => p.GetIndexParameters().Any() && p.GetIndexParameters()[0].ParameterType == typeof(int))
                        .Select(p => p.GetGetMethod()).First();
S
Sam Saffron 已提交
2156

2157
        /// <summary>
2158
        /// Gets type-map for the given type
2159
        /// </summary>
2160
        /// <returns>Type map implementation, DefaultTypeMap instance if no override present</returns>
2161
        public static ITypeMap GetTypeMap(Type type)
2162
        {
2163 2164
            if (type == null) throw new ArgumentNullException("type");
            var map = (ITypeMap)_typeMaps[type];
2165
            if (map == null)
2166
            {
2167
                lock (_typeMaps)
2168 2169 2170
                {   // double-checked; store this to avoid reflection next time we see this type
                    // since multiple queries commonly use the same domain-entity/DTO/view-model type
                    map = (ITypeMap)_typeMaps[type];
2171
                    if (map == null)
2172 2173 2174 2175 2176
                    {
                        map = new DefaultTypeMap(type);
                        _typeMaps[type] = map;
                    }
                }
2177
            }
2178
            return map;
2179 2180
        }

2181 2182
        // use Hashtable to get free lockless reading
        private static readonly Hashtable _typeMaps = new Hashtable();
2183 2184 2185 2186 2187 2188 2189

        /// <summary>
        /// Set custom mapping for type deserializers
        /// </summary>
        /// <param name="type">Entity type to override</param>
        /// <param name="map">Mapping rules impementation, null to remove custom map</param>
        public static void SetTypeMap(Type type, ITypeMap map)
2190
        {
2191 2192 2193 2194
            if (type == null)
                throw new ArgumentNullException("type");

            if (map == null || map is DefaultTypeMap)
2195
            {
2196
                lock (_typeMaps)
2197
                {
2198
                    _typeMaps.Remove(type);
2199 2200
                }
            }
2201
            else
2202
            {
2203
                lock (_typeMaps)
2204
                {
2205
                    _typeMaps[type] = map;
2206 2207
                }
            }
2208 2209

            PurgeQueryCacheByType(type);
2210 2211
        }

S
Sam Saffron 已提交
2212 2213 2214 2215 2216 2217 2218 2219 2220
        /// <summary>
        /// Internal use only
        /// </summary>
        /// <param name="type"></param>
        /// <param name="reader"></param>
        /// <param name="startBound"></param>
        /// <param name="length"></param>
        /// <param name="returnNullIfFirstMissing"></param>
        /// <returns></returns>
S
Sam Saffron 已提交
2221
        public static Func<IDataReader, object> GetTypeDeserializer(
M
mgravell 已提交
2222
#if CSHARP30
2223
Type type, IDataReader reader, int startBound, int length, bool returnNullIfFirstMissing
M
mgravell 已提交
2224
#else
2225
Type type, IDataReader reader, int startBound = 0, int length = -1, bool returnNullIfFirstMissing = false
2226 2227
#endif
)
S
Sam Saffron 已提交
2228
        {
2229

2230
            var dm = new DynamicMethod(string.Format("Deserialize{0}", Guid.NewGuid()), typeof(object), new[] { typeof(IDataReader) }, true);
S
Sam Saffron 已提交
2231
            var il = dm.GetILGenerator();
M
mgravell 已提交
2232
            il.DeclareLocal(typeof(int));
2233
            il.DeclareLocal(type);
M
mgravell 已提交
2234 2235
            il.Emit(OpCodes.Ldc_I4_0);
            il.Emit(OpCodes.Stloc_0);
2236

S
Sam Saffron 已提交
2237 2238 2239 2240 2241
            if (length == -1)
            {
                length = reader.FieldCount - startBound;
            }

2242 2243
            if (reader.FieldCount <= startBound)
            {
2244
                throw new ArgumentException(MultiMapSplitExceptionMessage, "splitOn");
2245 2246
            }

2247
            var names = Enumerable.Range(startBound, length).Select(i => reader.GetName(i)).ToArray();
2248

2249
            ITypeMap typeMap = GetTypeMap(type);
S
Sam Saffron 已提交
2250

S
Sam Saffron 已提交
2251
            int index = startBound;
S
Sam Saffron 已提交
2252

2253
            ConstructorInfo specializedConstructor = null;
2254

S
Sam Saffron 已提交
2255 2256
            if (type.IsValueType)
            {
2257
                il.Emit(OpCodes.Ldloca_S, (byte)1);
S
Sam Saffron 已提交
2258 2259 2260 2261
                il.Emit(OpCodes.Initobj, type);
            }
            else
            {
V
vosen 已提交
2262
                var types = new Type[length];
2263
                for (int i = startBound; i < startBound + length; i++)
2264
                {
2265 2266
                    types[i - startBound] = reader.GetFieldType(i);
                }
2267 2268

                if (type.IsValueType)
2269
                {
2270 2271 2272 2273 2274 2275 2276
                    il.Emit(OpCodes.Ldloca_S, (byte)1);
                    il.Emit(OpCodes.Initobj, type);
                }
                else
                {
                    var ctor = typeMap.FindConstructor(names, types);
                    if (ctor == null)
2277
                    {
2278 2279
                        string proposedTypes = "(" + String.Join(", ", types.Select((t, i) => t.FullName + " " + names[i]).ToArray()) + ")";
                        throw new InvalidOperationException(String.Format("A parameterless default constructor or one matching signature {0} is required for {1} materialization", proposedTypes, type.FullName));
2280 2281
                    }

2282
                    if (ctor.GetParameters().Length == 0)
2283
                    {
2284
                        il.Emit(OpCodes.Newobj, ctor);
2285
                        il.Emit(OpCodes.Stloc_1);
2286
                    }
2287
                    else
2288
                        specializedConstructor = ctor;
2289
                }
2290
            }
2291

2292
            il.BeginExceptionBlock();
2293
            if (type.IsValueType)
2294 2295
            {
                il.Emit(OpCodes.Ldloca_S, (byte)1);// [target]
2296
            }
2297
            else if (specializedConstructor == null)
2298 2299
            {
                il.Emit(OpCodes.Ldloc_1);// [target]
S
Sam Saffron 已提交
2300 2301
            }

2302
            var members = (specializedConstructor != null
2303 2304
                ? names.Select(n => typeMap.GetConstructorParameter(specializedConstructor, n))
                : names.Select(n => typeMap.GetMember(n))).ToList();
V
vosen 已提交
2305

S
Sam Saffron 已提交
2306 2307
            // stack is now [target]

2308
            bool first = true;
2309
            var allDone = il.DefineLabel();
2310
            int enumDeclareLocal = -1;
2311
            foreach (var item in members)
S
Sam Saffron 已提交
2312
            {
2313
                if (item != null)
S
Sam Saffron 已提交
2314
                {
2315
                    if (specializedConstructor == null)
2316
                        il.Emit(OpCodes.Dup); // stack is now [target][target]
S
Sam Saffron 已提交
2317 2318 2319 2320
                    Label isDbNullLabel = il.DefineLabel();
                    Label finishLabel = il.DefineLabel();

                    il.Emit(OpCodes.Ldarg_0); // stack is now [target][target][reader]
2321
                    EmitInt32(il, index); // stack is now [target][target][reader][index]
M
mgravell 已提交
2322 2323
                    il.Emit(OpCodes.Dup);// stack is now [target][target][reader][index][index]
                    il.Emit(OpCodes.Stloc_0);// stack is now [target][target][reader][index]
S
Sam Saffron 已提交
2324 2325
                    il.Emit(OpCodes.Callvirt, getItem); // stack is now [target][target][value-as-object]

2326
                    Type memberType = item.MemberType;
M
mgravell 已提交
2327

M
mgravell 已提交
2328
                    if (memberType == typeof(char) || memberType == typeof(char?))
M
mgravell 已提交
2329
                    {
M
mgravell 已提交
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339
                        il.EmitCall(OpCodes.Call, typeof(SqlMapper).GetMethod(
                            memberType == typeof(char) ? "ReadChar" : "ReadNullableChar", BindingFlags.Static | BindingFlags.Public), null); // stack is now [target][target][typed-value]
                    }
                    else
                    {
                        il.Emit(OpCodes.Dup); // stack is now [target][target][value][value]
                        il.Emit(OpCodes.Isinst, typeof(DBNull)); // stack is now [target][target][value-as-object][DBNull or null]
                        il.Emit(OpCodes.Brtrue_S, isDbNullLabel); // stack is now [target][target][value-as-object]

                        // unbox nullable enums as the primitive, i.e. byte etc
2340

M
mgravell 已提交
2341 2342 2343 2344
                        var nullUnderlyingType = Nullable.GetUnderlyingType(memberType);
                        var unboxType = nullUnderlyingType != null && nullUnderlyingType.IsEnum ? nullUnderlyingType : memberType;

                        if (unboxType.IsEnum)
M
mgravell 已提交
2345
                        {
2346
                            if (enumDeclareLocal == -1)
M
mgravell 已提交
2347
                            {
2348
                                enumDeclareLocal = il.DeclareLocal(typeof(string)).LocalIndex;
M
mgravell 已提交
2349
                            }
M
mgravell 已提交
2350

M
mgravell 已提交
2351 2352 2353 2354
                            Label isNotString = il.DefineLabel();
                            il.Emit(OpCodes.Dup); // stack is now [target][target][value][value]
                            il.Emit(OpCodes.Isinst, typeof(string)); // stack is now [target][target][value-as-object][string or null]
                            il.Emit(OpCodes.Dup);// stack is now [target][target][value-as-object][string or null][string or null]
2355
                            StoreLocal(il, enumDeclareLocal); // stack is now [target][target][value-as-object][string or null]
M
mgravell 已提交
2356
                            il.Emit(OpCodes.Brfalse_S, isNotString); // stack is now [target][target][value-as-object]
M
mgravell 已提交
2357

M
mgravell 已提交
2358
                            il.Emit(OpCodes.Pop); // stack is now [target][target]
M
mgravell 已提交
2359

M
mgravell 已提交
2360 2361 2362 2363 2364
                            il.Emit(OpCodes.Ldtoken, unboxType); // stack is now [target][target][enum-type-token]
                            il.EmitCall(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"), null);// stack is now [target][target][enum-type]
                            il.Emit(OpCodes.Ldloc_2); // stack is now [target][target][enum-type][string]
                            il.Emit(OpCodes.Ldc_I4_1); // stack is now [target][target][enum-type][string][true]
                            il.EmitCall(OpCodes.Call, enumParse, null); // stack is now [target][target][enum-as-object]
M
mgravell 已提交
2365

2366 2367
                            il.MarkLabel(isNotString);

M
mgravell 已提交
2368
                            il.Emit(OpCodes.Unbox_Any, unboxType); // stack is now [target][target][typed-value]
M
mgravell 已提交
2369

M
mgravell 已提交
2370
                            if (nullUnderlyingType != null)
2371
                            {
2372
                                il.Emit(OpCodes.Newobj, memberType.GetConstructor(new[] { nullUnderlyingType })); // stack is now [target][target][enum-value]
M
mgravell 已提交
2373
                            }
M
mgravell 已提交
2374
                        }
2375
                        else if (memberType.FullName == LinqBinary)
M
mgravell 已提交
2376 2377
                        {
                            il.Emit(OpCodes.Unbox_Any, typeof(byte[])); // stack is now [target][target][byte-array]
M
mgravell 已提交
2378
                            il.Emit(OpCodes.Newobj, memberType.GetConstructor(new Type[] { typeof(byte[]) }));// stack is now [target][target][binary]
M
mgravell 已提交
2379 2380 2381
                        }
                        else
                        {
2382 2383 2384 2385 2386 2387 2388 2389 2390
                            Type dataType = reader.GetFieldType(index);
                            TypeCode dataTypeCode = Type.GetTypeCode(dataType), unboxTypeCode = Type.GetTypeCode(unboxType);
                            if (dataType == unboxType || dataTypeCode == unboxTypeCode || dataTypeCode == Type.GetTypeCode(nullUnderlyingType))
                            {
                                il.Emit(OpCodes.Unbox_Any, unboxType); // stack is now [target][target][typed-value]
                            }
                            else
                            {
                                // not a direct match; need to tweak the unbox
2391 2392 2393 2394 2395
                                MethodInfo op;
                                if ((op = GetOperator(dataType, nullUnderlyingType ?? unboxType)) != null)
                                { // this is handy for things like decimal <===> double
                                    il.Emit(OpCodes.Unbox_Any, dataType); // stack is now [target][target][data-typed-value]
                                    il.Emit(OpCodes.Call, op); // stack is now [target][target][typed-value]
2396 2397 2398
                                }
                                else
                                {
2399 2400 2401 2402 2403 2404 2405 2406
                                    bool handled = true;
                                    OpCode opCode = default(OpCode);
                                    if (dataTypeCode == TypeCode.Decimal || unboxTypeCode == TypeCode.Decimal)
                                    {   // no IL level conversions to/from decimal; I guess we could use the static operators, but
                                        // this feels an edge-case
                                        handled = false;
                                    }
                                    else
2407
                                    {
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434
                                        switch (unboxTypeCode)
                                        {
                                            case TypeCode.Byte:
                                                opCode = OpCodes.Conv_Ovf_I1_Un; break;
                                            case TypeCode.SByte:
                                                opCode = OpCodes.Conv_Ovf_I1; break;
                                            case TypeCode.UInt16:
                                                opCode = OpCodes.Conv_Ovf_I2_Un; break;
                                            case TypeCode.Int16:
                                                opCode = OpCodes.Conv_Ovf_I2; break;
                                            case TypeCode.UInt32:
                                                opCode = OpCodes.Conv_Ovf_I4_Un; break;
                                            case TypeCode.Boolean: // boolean is basically an int, at least at this level
                                            case TypeCode.Int32:
                                                opCode = OpCodes.Conv_Ovf_I4; break;
                                            case TypeCode.UInt64:
                                                opCode = OpCodes.Conv_Ovf_I8_Un; break;
                                            case TypeCode.Int64:
                                                opCode = OpCodes.Conv_Ovf_I8; break;
                                            case TypeCode.Single:
                                                opCode = OpCodes.Conv_R4; break;
                                            case TypeCode.Double:
                                                opCode = OpCodes.Conv_R8; break;
                                            default:
                                                handled = false;
                                                break;
                                        }
2435
                                    }
2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
                                    if (handled)
                                    { // unbox as the data-type, then use IL-level convert
                                        il.Emit(OpCodes.Unbox_Any, dataType); // stack is now [target][target][data-typed-value]
                                        il.Emit(opCode); // stack is now [target][target][typed-value]
                                        if (unboxTypeCode == TypeCode.Boolean)
                                        { // compare to zero; I checked "csc" - this is the trick it uses; nice
                                            il.Emit(OpCodes.Ldc_I4_0);
                                            il.Emit(OpCodes.Ceq);
                                            il.Emit(OpCodes.Ldc_I4_0);
                                            il.Emit(OpCodes.Ceq);
                                        }
                                    }
                                    else
                                    { // use flexible conversion
                                        il.Emit(OpCodes.Ldtoken, nullUnderlyingType ?? unboxType); // stack is now [target][target][value][member-type-token]
                                        il.EmitCall(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"), null); // stack is now [target][target][value][member-type]
                                        il.EmitCall(OpCodes.Call, typeof(Convert).GetMethod("ChangeType", new Type[] { typeof(object), typeof(Type) }), null); // stack is now [target][target][boxed-member-type-value]
                                        il.Emit(OpCodes.Unbox_Any, nullUnderlyingType ?? unboxType); // stack is now [target][target][typed-value]
2454
                                    }
2455
                                }
2456 2457 2458
                                if (nullUnderlyingType != null)
                                {
                                    il.Emit(OpCodes.Newobj, unboxType.GetConstructor(new[] { nullUnderlyingType })); // stack is now [target][target][typed-value]
2459
                                }
2460

2461
                            }
2462

M
mgravell 已提交
2463
                        }
2464 2465
                    }
                    if (specializedConstructor == null)
M
mgravell 已提交
2466
                    {
2467
                        // Store the value in the property/field
2468
                        if (item.Property != null)
S
Sam Saffron 已提交
2469
                        {
2470 2471
                            if (type.IsValueType)
                            {
2472
                                il.Emit(OpCodes.Call, DefaultTypeMap.GetPropertySetter(item.Property, type)); // stack is now [target]
2473 2474 2475
                            }
                            else
                            {
2476
                                il.Emit(OpCodes.Callvirt, DefaultTypeMap.GetPropertySetter(item.Property, type)); // stack is now [target]
2477
                            }
S
Sam Saffron 已提交
2478 2479 2480
                        }
                        else
                        {
2481
                            il.Emit(OpCodes.Stfld, item.Field); // stack is now [target]
S
Sam Saffron 已提交
2482
                        }
M
mgravell 已提交
2483
                    }
2484

S
Sam Saffron 已提交
2485
                    il.Emit(OpCodes.Br_S, finishLabel); // stack is now [target]
2486

S
Sam Saffron 已提交
2487
                    il.MarkLabel(isDbNullLabel); // incoming stack: [target][target][value]
2488
                    if (specializedConstructor != null)
M
mgravell 已提交
2489
                    {
V
vosen 已提交
2490
                        il.Emit(OpCodes.Pop);
2491
                        if (item.MemberType.IsValueType)
S
Sam Saffron 已提交
2492
                        {
2493
                            int localIndex = il.DeclareLocal(item.MemberType).LocalIndex;
2494
                            LoadLocalAddress(il, localIndex);
2495
                            il.Emit(OpCodes.Initobj, item.MemberType);
2496
                            LoadLocal(il, localIndex);
S
Sam Saffron 已提交
2497 2498 2499
                        }
                        else
                        {
2500
                            il.Emit(OpCodes.Ldnull);
S
Sam Saffron 已提交
2501
                        }
M
mgravell 已提交
2502 2503 2504
                    }
                    else
                    {
2505 2506
                        il.Emit(OpCodes.Pop); // stack is now [target][target]
                        il.Emit(OpCodes.Pop); // stack is now [target]
M
mgravell 已提交
2507
                    }
S
Sam Saffron 已提交
2508

2509 2510 2511 2512
                    if (first && returnNullIfFirstMissing)
                    {
                        il.Emit(OpCodes.Pop);
                        il.Emit(OpCodes.Ldnull); // stack is now [null]
M
mgravell 已提交
2513
                        il.Emit(OpCodes.Stloc_1);
2514
                        il.Emit(OpCodes.Br, allDone);
2515 2516
                    }

S
Sam Saffron 已提交
2517 2518
                    il.MarkLabel(finishLabel);
                }
2519
                first = false;
2520
                index += 1;
S
Sam Saffron 已提交
2521
            }
S
Sam Saffron 已提交
2522 2523 2524 2525 2526 2527
            if (type.IsValueType)
            {
                il.Emit(OpCodes.Pop);
            }
            else
            {
2528 2529 2530 2531
                if (specializedConstructor != null)
                {
                    il.Emit(OpCodes.Newobj, specializedConstructor);
                }
S
Sam Saffron 已提交
2532 2533
                il.Emit(OpCodes.Stloc_1); // stack is empty
            }
2534
            il.MarkLabel(allDone);
M
mgravell 已提交
2535 2536 2537 2538 2539 2540
            il.BeginCatchBlock(typeof(Exception)); // stack is Exception
            il.Emit(OpCodes.Ldloc_0); // stack is Exception, index
            il.Emit(OpCodes.Ldarg_0); // stack is Exception, index, reader
            il.EmitCall(OpCodes.Call, typeof(SqlMapper).GetMethod("ThrowDataException"), null);
            il.EndExceptionBlock();

2541
            il.Emit(OpCodes.Ldloc_1); // stack is [rval]
2542
            if (type.IsValueType)
S
Sam Saffron 已提交
2543 2544 2545
            {
                il.Emit(OpCodes.Box, type);
            }
M
mgravell 已提交
2546
            il.Emit(OpCodes.Ret);
S
Sam Saffron 已提交
2547

2548
            return (Func<IDataReader, object>)dm.CreateDelegate(typeof(Func<IDataReader, object>));
S
Sam Saffron 已提交
2549
        }
2550 2551 2552 2553 2554 2555 2556 2557
        static MethodInfo GetOperator(Type from, Type to)
        {
            if (to == null) return null;
            MethodInfo[] fromMethods, toMethods;
            return ResolveOperator(fromMethods = from.GetMethods(BindingFlags.Static | BindingFlags.Public), from, to, "op_Implicit")
                ?? ResolveOperator(toMethods = to.GetMethods(BindingFlags.Static | BindingFlags.Public), from, to, "op_Implicit")
                ?? ResolveOperator(fromMethods, from, to, "op_Explicit")
                ?? ResolveOperator(toMethods, from, to, "op_Explicit");
2558

2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570
        }
        static MethodInfo ResolveOperator(MethodInfo[] methods, Type from, Type to, string name)
        {
            for (int i = 0; i < methods.Length; i++)
            {
                if (methods[i].Name != name || methods[i].ReturnType != to) continue;
                var args = methods[i].GetParameters();
                if (args.Length != 1 || args[0].ParameterType != from) continue;
                return methods[i];
            }
            return null;
        }
S
Sam Saffron 已提交
2571

2572 2573
        private static void LoadLocal(ILGenerator il, int index)
        {
2574 2575
            if (index < 0 || index >= short.MaxValue) throw new ArgumentNullException("index");
            switch (index)
2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616
            {
                case 0: il.Emit(OpCodes.Ldloc_0); break;
                case 1: il.Emit(OpCodes.Ldloc_1); break;
                case 2: il.Emit(OpCodes.Ldloc_2); break;
                case 3: il.Emit(OpCodes.Ldloc_3); break;
                default:
                    if (index <= 255)
                    {
                        il.Emit(OpCodes.Ldloc_S, (byte)index);
                    }
                    else
                    {
                        il.Emit(OpCodes.Ldloc, (short)index);
                    }
                    break;
            }
        }
        private static void StoreLocal(ILGenerator il, int index)
        {
            if (index < 0 || index >= short.MaxValue) throw new ArgumentNullException("index");
            switch (index)
            {
                case 0: il.Emit(OpCodes.Stloc_0); break;
                case 1: il.Emit(OpCodes.Stloc_1); break;
                case 2: il.Emit(OpCodes.Stloc_2); break;
                case 3: il.Emit(OpCodes.Stloc_3); break;
                default:
                    if (index <= 255)
                    {
                        il.Emit(OpCodes.Stloc_S, (byte)index);
                    }
                    else
                    {
                        il.Emit(OpCodes.Stloc, (short)index);
                    }
                    break;
            }
        }
        private static void LoadLocalAddress(ILGenerator il, int index)
        {
            if (index < 0 || index >= short.MaxValue) throw new ArgumentNullException("index");
2617

2618 2619 2620 2621 2622 2623 2624 2625 2626
            if (index <= 255)
            {
                il.Emit(OpCodes.Ldloca_S, (byte)index);
            }
            else
            {
                il.Emit(OpCodes.Ldloca, (short)index);
            }
        }
S
Sam Saffron 已提交
2627 2628 2629 2630 2631 2632
        /// <summary>
        /// Throws a data exception, only used internally
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="index"></param>
        /// <param name="reader"></param>
M
mgravell 已提交
2633 2634
        public static void ThrowDataException(Exception ex, int index, IDataReader reader)
        {
2635 2636
            Exception toThrow;
            try
M
mgravell 已提交
2637
            {
2638 2639
                string name = "(n/a)", value = "(n/a)";
                if (reader != null && index >= 0 && index < reader.FieldCount)
M
mgravell 已提交
2640
                {
2641 2642 2643 2644 2645 2646 2647 2648 2649 2650
                    name = reader.GetName(index);
                    object val = reader.GetValue(index);
                    if (val == null || val is DBNull)
                    {
                        value = "<null>";
                    }
                    else
                    {
                        value = Convert.ToString(val) + " - " + Type.GetTypeCode(val.GetType());
                    }
M
mgravell 已提交
2651
                }
2652
                toThrow = new DataException(string.Format("Error parsing column {0} ({1}={2})", index, name, value), ex);
2653 2654
            }
            catch
2655
            { // throw the **original** exception, wrapped as DataException
2656
                toThrow = new DataException(ex.Message, ex);
M
mgravell 已提交
2657
            }
2658
            throw toThrow;
M
mgravell 已提交
2659
        }
S
Sam Saffron 已提交
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673
        private static void EmitInt32(ILGenerator il, int value)
        {
            switch (value)
            {
                case -1: il.Emit(OpCodes.Ldc_I4_M1); break;
                case 0: il.Emit(OpCodes.Ldc_I4_0); break;
                case 1: il.Emit(OpCodes.Ldc_I4_1); break;
                case 2: il.Emit(OpCodes.Ldc_I4_2); break;
                case 3: il.Emit(OpCodes.Ldc_I4_3); break;
                case 4: il.Emit(OpCodes.Ldc_I4_4); break;
                case 5: il.Emit(OpCodes.Ldc_I4_5); break;
                case 6: il.Emit(OpCodes.Ldc_I4_6); break;
                case 7: il.Emit(OpCodes.Ldc_I4_7); break;
                case 8: il.Emit(OpCodes.Ldc_I4_8); break;
M
Marc Gravell 已提交
2674 2675 2676 2677 2678 2679 2680 2681 2682 2683
                default:
                    if (value >= -128 && value <= 127)
                    {
                        il.Emit(OpCodes.Ldc_I4_S, (sbyte)value);
                    }
                    else
                    {
                        il.Emit(OpCodes.Ldc_I4, value);
                    }
                    break;
S
Sam Saffron 已提交
2684 2685
            }
        }
M
mgravell 已提交
2686

2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700

        /// <summary>
        /// How should connection strings be compared for equivalence? Defaults to StringComparer.Ordinal.
        /// Providing a custom implementation can be useful for allowing multi-tenancy databases with identical
        /// schema to share startegies. Note that usual equivalence rules apply: any equivalent connection strings
        /// <b>MUST</b> yield the same hash-code.
        /// </summary>
        public static IEqualityComparer<string> ConnectionStringComparer
        {
            get { return connectionStringComparer; }
            set { connectionStringComparer = value ?? StringComparer.Ordinal; }
        }
        private static IEqualityComparer<string> connectionStringComparer = StringComparer.Ordinal;

S
Sam Saffron 已提交
2701 2702 2703
        /// <summary>
        /// The grid reader provides interfaces for reading multiple result sets from a Dapper query 
        /// </summary>
2704
        public partial class GridReader : IDisposable
M
mgravell 已提交
2705 2706 2707
        {
            private IDataReader reader;
            private IDbCommand command;
2708
            private Identity identity;
2709

2710
            internal GridReader(IDbCommand command, IDataReader reader, Identity identity)
M
mgravell 已提交
2711 2712 2713
            {
                this.command = command;
                this.reader = reader;
2714
                this.identity = identity;
M
mgravell 已提交
2715
            }
2716 2717 2718 2719 2720 2721

#if !CSHARP30

            /// <summary>
            /// Read the next grid of results, returned as a dynamic object
            /// </summary>
2722
            public IEnumerable<dynamic> Read(bool buffered = true)
2723
            {
2724
                return Read<DapperRow>(buffered);
2725 2726 2727
            }
#endif

2728
#if CSHARP30
M
mgravell 已提交
2729 2730 2731 2732
            /// <summary>
            /// Read the next grid of results
            /// </summary>
            public IEnumerable<T> Read<T>()
2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744
            {
                return Read<T>(true);
            }
#endif
            /// <summary>
            /// Read the next grid of results
            /// </summary>
#if CSHARP30
            public IEnumerable<T> Read<T>(bool buffered)
#else
            public IEnumerable<T> Read<T>(bool buffered = true)
#endif
M
mgravell 已提交
2745
            {
2746
                if (reader == null) throw new ObjectDisposedException(GetType().FullName, "The reader has been disposed; this can happen after all data has been consumed");
2747
                if (consumed) throw new InvalidOperationException("Query results must be consumed in the correct order, and each result can only be consumed once");
2748 2749
                var typedIdentity = identity.ForGrid(typeof(T), gridIndex);
                CacheInfo cache = GetCacheInfo(typedIdentity);
M
mgravell 已提交
2750
                var deserializer = cache.Deserializer;
S
Sam Saffron 已提交
2751

2752 2753
                int hash = GetColumnHash(reader);
                if (deserializer.Func == null || deserializer.Hash != hash)
2754
                {
2755
                    deserializer = new DeserializerState(hash, GetDeserializer(typeof(T), reader, 0, -1, false));
2756 2757
                    cache.Deserializer = deserializer;
                }
M
mgravell 已提交
2758
                consumed = true;
2759 2760
                var result = ReadDeferred<T>(gridIndex, deserializer.Func, typedIdentity);
                return buffered ? result.ToList() : result;
M
mgravell 已提交
2761
            }
S
Sam Saffron 已提交
2762

2763
            private IEnumerable<TReturn> MultiReadInternal<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(object func, string splitOn)
2764 2765 2766 2767 2768 2769
            {
                var identity = this.identity.ForGrid(typeof(TReturn), new Type[] { 
                    typeof(TFirst), 
                    typeof(TSecond),
                    typeof(TThird),
                    typeof(TFourth),
2770 2771 2772
                    typeof(TFifth),
                    typeof(TSixth),
                    typeof(TSeventh)
2773 2774 2775
                }, gridIndex);
                try
                {
2776
                    foreach (var r in SqlMapper.MultiMapImpl<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(null, null, func, null, null, splitOn, null, null, reader, identity))
2777 2778 2779 2780 2781 2782 2783 2784 2785 2786
                    {
                        yield return r;
                    }
                }
                finally
                {
                    NextResult();
                }
            }

2787
#if CSHARP30
S
Sam Saffron 已提交
2788 2789 2790
            /// <summary>
            /// Read multiple objects from a single recordset on the grid
            /// </summary>
2791
            public IEnumerable<TReturn> Read<TFirst, TSecond, TReturn>(Func<TFirst, TSecond, TReturn> func, string splitOn)
2792 2793 2794 2795 2796 2797 2798
            {
                return Read<TFirst, TSecond, TReturn>(func, splitOn, true);
            }
#endif
            /// <summary>
            /// Read multiple objects from a single recordset on the grid
            /// </summary>
2799
#if CSHARP30
2800
            public IEnumerable<TReturn> Read<TFirst, TSecond, TReturn>(Func<TFirst, TSecond, TReturn> func, string splitOn, bool buffered)
2801
#else
2802
            public IEnumerable<TReturn> Read<TFirst, TSecond, TReturn>(Func<TFirst, TSecond, TReturn> func, string splitOn = "id", bool buffered = true)
2803 2804
#endif
            {
2805
                var result = MultiReadInternal<TFirst, TSecond, DontMap, DontMap, DontMap, DontMap, DontMap, TReturn>(func, splitOn);
2806
                return buffered ? result.ToList() : result;
2807 2808
            }

2809
#if CSHARP30
S
Sam Saffron 已提交
2810 2811 2812
            /// <summary>
            /// Read multiple objects from a single recordset on the grid
            /// </summary>
2813
            public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TReturn>(Func<TFirst, TSecond, TThird, TReturn> func, string splitOn)
2814 2815 2816 2817 2818 2819 2820
            {
                return Read<TFirst, TSecond, TThird, TReturn>(func, splitOn, true);
            }
#endif
            /// <summary>
            /// Read multiple objects from a single recordset on the grid
            /// </summary>
2821
#if CSHARP30
2822
            public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TReturn>(Func<TFirst, TSecond, TThird, TReturn> func, string splitOn, bool buffered)
2823
#else
2824
            public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TReturn>(Func<TFirst, TSecond, TThird, TReturn> func, string splitOn = "id", bool buffered = true)
2825 2826
#endif
            {
2827
                var result = MultiReadInternal<TFirst, TSecond, TThird, DontMap, DontMap, DontMap, DontMap, TReturn>(func, splitOn);
2828
                return buffered ? result.ToList() : result;
2829 2830
            }

2831
#if CSHARP30
S
Sam Saffron 已提交
2832 2833 2834
            /// <summary>
            /// Read multiple objects from a single record set on the grid
            /// </summary>
2835
            public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TFourth, TReturn>(Func<TFirst, TSecond, TThird, TFourth, TReturn> func, string splitOn)
2836 2837 2838 2839 2840 2841 2842 2843
            {
                return Read<TFirst, TSecond, TThird, TFourth, TReturn>(func, splitOn, true);
            }
#endif

            /// <summary>
            /// Read multiple objects from a single record set on the grid
            /// </summary>
2844
#if CSHARP30
2845
            public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TFourth, TReturn>(Func<TFirst, TSecond, TThird, TFourth, TReturn> func, string splitOn, bool buffered)
2846
#else
2847
            public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TFourth, TReturn>(Func<TFirst, TSecond, TThird, TFourth, TReturn> func, string splitOn = "id", bool buffered = true)
2848 2849
#endif
            {
2850
                var result = MultiReadInternal<TFirst, TSecond, TThird, TFourth, DontMap, DontMap, DontMap, TReturn>(func, splitOn);
2851
                return buffered ? result.ToList() : result;
2852 2853
            }

2854 2855


2856
#if !CSHARP30
S
Sam Saffron 已提交
2857 2858 2859
            /// <summary>
            /// Read multiple objects from a single record set on the grid
            /// </summary>
2860
            public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn> func, string splitOn = "id", bool buffered = true)
2861
            {
2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878
                var result = MultiReadInternal<TFirst, TSecond, TThird, TFourth, TFifth, DontMap, DontMap, TReturn>(func, splitOn);
                return buffered ? result.ToList() : result;
            }
            /// <summary>
            /// Read multiple objects from a single record set on the grid
            /// </summary>
            public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn>(Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn> func, string splitOn = "id", bool buffered = true)
            {
                var result = MultiReadInternal<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, DontMap, TReturn>(func, splitOn);
                return buffered ? result.ToList() : result;
            }
            /// <summary>
            /// Read multiple objects from a single record set on the grid
            /// </summary>
            public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn> func, string splitOn = "id", bool buffered = true)
            {
                var result = MultiReadInternal<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(func, splitOn);
2879
                return buffered ? result.ToList() : result;
2880 2881
            }
#endif
S
Sam Saffron 已提交
2882

2883
            private IEnumerable<T> ReadDeferred<T>(int index, Func<IDataReader, object> deserializer, Identity typedIdentity)
M
mgravell 已提交
2884 2885 2886 2887 2888
            {
                try
                {
                    while (index == gridIndex && reader.Read())
                    {
2889
                        yield return (T)deserializer(reader);
M
mgravell 已提交
2890 2891 2892 2893 2894 2895 2896 2897 2898 2899
                    }
                }
                finally // finally so that First etc progresses things even when multiple rows
                {
                    if (index == gridIndex)
                    {
                        NextResult();
                    }
                }
            }
2900
            private int gridIndex, readCount;
M
mgravell 已提交
2901 2902 2903 2904 2905
            private bool consumed;
            private void NextResult()
            {
                if (reader.NextResult())
                {
2906
                    readCount++;
M
mgravell 已提交
2907 2908 2909 2910 2911
                    gridIndex++;
                    consumed = false;
                }
                else
                {
2912 2913 2914 2915 2916
                    // happy path; close the reader cleanly - no
                    // need for "Cancel" etc
                    reader.Dispose();
                    reader = null;

M
mgravell 已提交
2917 2918 2919 2920
                    Dispose();
                }

            }
S
Sam Saffron 已提交
2921 2922 2923
            /// <summary>
            /// Dispose the grid, closing and disposing both the underlying reader and command.
            /// </summary>
M
mgravell 已提交
2924 2925 2926 2927
            public void Dispose()
            {
                if (reader != null)
                {
2928
                    if (!reader.IsClosed && command != null) command.Cancel();
M
mgravell 已提交
2929 2930 2931 2932 2933 2934 2935 2936 2937 2938
                    reader.Dispose();
                    reader = null;
                }
                if (command != null)
                {
                    command.Dispose();
                    command = null;
                }
            }
        }
S
Sam Saffron 已提交
2939
    }
S
Sam Saffron 已提交
2940 2941 2942 2943

    /// <summary>
    /// A bag of parameters that can be passed to the Dapper Query and Execute methods
    /// </summary>
2944
    partial class DynamicParameters : SqlMapper.IDynamicParameters
S
Sam Saffron 已提交
2945
    {
2946
        internal const DbType EnumerableMultiParameter = (DbType)(-1);
2947 2948
        static Dictionary<SqlMapper.Identity, Action<IDbCommand, object>> paramReaderCache = new Dictionary<SqlMapper.Identity, Action<IDbCommand, object>>();

2949
        Dictionary<string, ParamInfo> parameters = new Dictionary<string, ParamInfo>();
2950
        List<object> templates;
S
Sam Saffron 已提交
2951

2952
        partial class ParamInfo
S
Sam Saffron 已提交
2953 2954 2955 2956 2957 2958 2959 2960 2961
        {
            public string Name { get; set; }
            public object Value { get; set; }
            public ParameterDirection ParameterDirection { get; set; }
            public DbType? DbType { get; set; }
            public int? Size { get; set; }
            public IDbDataParameter AttachedParam { get; set; }
        }

S
Sam Saffron 已提交
2962 2963 2964
        /// <summary>
        /// construct a dynamic parameter bag
        /// </summary>
2965 2966 2967 2968
        public DynamicParameters()
        {
            RemoveUnused = true;
        }
2969

S
Sam Saffron 已提交
2970 2971 2972
        /// <summary>
        /// construct a dynamic parameter bag
        /// </summary>
2973
        /// <param name="template">can be an anonymous type or a DynamicParameters bag</param>
2974 2975
        public DynamicParameters(object template)
        {
2976
            RemoveUnused = true;
2977
            AddDynamicParams(template);
2978 2979 2980 2981
        }

        /// <summary>
        /// Append a whole object full of params to the dynamic
2982
        /// EG: AddDynamicParams(new {A = 1, B = 2}) // will add property A and B to the dynamic
2983 2984 2985 2986
        /// </summary>
        /// <param name="param"></param>
        public void AddDynamicParams(
#if CSHARP30
2987
object param
2988
#else
2989
dynamic param
2990
#endif
2991
)
2992
        {
2993
            var obj = param as object;
2994
            if (obj != null)
2995 2996 2997 2998
            {
                var subDynamic = obj as DynamicParameters;
                if (subDynamic == null)
                {
2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015
                    var dictionary = obj as IEnumerable<KeyValuePair<string, object>>;
                    if (dictionary == null)
                    {
                        templates = templates ?? new List<object>();
                        templates.Add(obj);
                    }
                    else
                    {
                        foreach (var kvp in dictionary)
                        {
#if CSHARP30
                            Add(kvp.Key, kvp.Value, null, null, null);
#else
                            Add(kvp.Key, kvp.Value);
#endif
                        }
                    }
3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028
                }
                else
                {
                    if (subDynamic.parameters != null)
                    {
                        foreach (var kvp in subDynamic.parameters)
                        {
                            parameters.Add(kvp.Key, kvp.Value);
                        }
                    }

                    if (subDynamic.templates != null)
                    {
3029
                        templates = templates ?? new List<object>();
3030 3031 3032 3033 3034 3035
                        foreach (var t in subDynamic.templates)
                        {
                            templates.Add(t);
                        }
                    }
                }
3036 3037 3038
            }
        }

S
Sam Saffron 已提交
3039 3040 3041 3042 3043 3044 3045 3046
        /// <summary>
        /// Add a parameter to this dynamic parameter list
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="dbType"></param>
        /// <param name="direction"></param>
        /// <param name="size"></param>
M
mgravell 已提交
3047 3048
        public void Add(
#if CSHARP30
3049
string name, object value, DbType? dbType, ParameterDirection? direction, int? size
M
mgravell 已提交
3050
#else
3051 3052 3053
string name, object value = null, DbType? dbType = null, ParameterDirection? direction = null, int? size = null
#endif
)
S
Sam Saffron 已提交
3054
        {
3055
            parameters[Clean(name)] = new ParamInfo() { Name = name, Value = value, ParameterDirection = direction ?? ParameterDirection.Input, DbType = dbType, Size = size };
S
Sam Saffron 已提交
3056 3057
        }

3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071
        static string Clean(string name)
        {
            if (!string.IsNullOrEmpty(name))
            {
                switch (name[0])
                {
                    case '@':
                    case ':':
                    case '?':
                        return name.Substring(1);
                }
            }
            return name;
        }
S
Sam Saffron 已提交
3072

3073
        void SqlMapper.IDynamicParameters.AddParameters(IDbCommand command, SqlMapper.Identity identity)
3074 3075 3076 3077
        {
            AddParameters(command, identity);
        }

3078 3079 3080 3081 3082
        /// <summary>
        /// If true, the command-text is inspected and only values that are clearly used are included on the connection
        /// </summary>
        public bool RemoveUnused { get; set; }

3083 3084 3085 3086 3087 3088
        /// <summary>
        /// Add all the parameters needed to the command just before it executes
        /// </summary>
        /// <param name="command">The raw command prior to execution</param>
        /// <param name="identity">Information about the query</param>
        protected void AddParameters(IDbCommand command, SqlMapper.Identity identity)
S
Sam Saffron 已提交
3089
        {
3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100
            if (templates != null)
            {
                foreach (var template in templates)
                {
                    var newIdent = identity.ForDynamicParameters(template.GetType());
                    Action<IDbCommand, object> appender;

                    lock (paramReaderCache)
                    {
                        if (!paramReaderCache.TryGetValue(newIdent, out appender))
                        {
3101
                            appender = SqlMapper.CreateParamInfoGenerator(newIdent, true, RemoveUnused);
3102 3103 3104 3105 3106 3107 3108 3109
                            paramReaderCache[newIdent] = appender;
                        }
                    }

                    appender(command, template);
                }
            }

S
Sam Saffron 已提交
3110 3111
            foreach (var param in parameters.Values)
            {
3112 3113
                var dbType = param.DbType;
                var val = param.Value;
3114
                string name = Clean(param.Name);
3115 3116 3117

                if (dbType == null && val != null) dbType = SqlMapper.LookupDbType(val.GetType(), name);

3118 3119
                if (dbType == DynamicParameters.EnumerableMultiParameter)
                {
3120 3121 3122
#pragma warning disable 612, 618
                    SqlMapper.PackListParameters(command, name, val);
#pragma warning restore 612, 618
3123
                }
3124
                else
S
Sam Saffron 已提交
3125
                {
3126 3127 3128 3129

                    bool add = !command.Parameters.Contains(name);
                    IDbDataParameter p;
                    if (add)
S
Sam Saffron 已提交
3130
                    {
3131 3132
                        p = command.CreateParameter();
                        p.ParameterName = name;
S
Sam Saffron 已提交
3133
                    }
3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161
                    else
                    {
                        p = (IDbDataParameter)command.Parameters[name];
                    }

                    p.Value = val ?? DBNull.Value;
                    p.Direction = param.ParameterDirection;
                    var s = val as string;
                    if (s != null)
                    {
                        if (s.Length <= 4000)
                        {
                            p.Size = 4000;
                        }
                    }
                    if (param.Size != null)
                    {
                        p.Size = param.Size.Value;
                    }
                    if (dbType != null)
                    {
                        p.DbType = dbType.Value;
                    }
                    if (add)
                    {
                        command.Parameters.Add(p);
                    }
                    param.AttachedParam = p;
S
Sam Saffron 已提交
3162
                }
3163

S
Sam Saffron 已提交
3164 3165 3166
            }
        }

S
Sam Saffron 已提交
3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178
        /// <summary>
        /// All the names of the param in the bag, use Get to yank them out
        /// </summary>
        public IEnumerable<string> ParameterNames
        {
            get
            {
                return parameters.Select(p => p.Key);
            }
        }


S
Sam Saffron 已提交
3179 3180 3181 3182 3183 3184
        /// <summary>
        /// Get the value of a parameter
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <returns>The value, note DBNull.Value is not returned, instead the value is returned as null</returns>
S
Sam Saffron 已提交
3185
        public T Get<T>(string name)
S
Sam Saffron 已提交
3186
        {
3187 3188 3189 3190 3191 3192 3193 3194 3195 3196
            var val = parameters[Clean(name)].AttachedParam.Value;
            if (val == DBNull.Value)
            {
                if (default(T) != null)
                {
                    throw new ApplicationException("Attempting to cast a DBNull to a non nullable type!");
                }
                return default(T);
            }
            return (T)val;
S
Sam Saffron 已提交
3197 3198
        }
    }
S
Sam Saffron 已提交
3199 3200 3201 3202

    /// <summary>
    /// This class represents a SQL string, it can be used if you need to denote your parameter is a Char vs VarChar vs nVarChar vs nChar
    /// </summary>
3203
    sealed partial class DbString : Dapper.SqlMapper.ICustomQueryParameter
M
mgravell 已提交
3204
    {
S
Sam Saffron 已提交
3205 3206 3207
        /// <summary>
        /// Create a new DbString
        /// </summary>
M
mgravell 已提交
3208
        public DbString() { Length = -1; }
S
Sam Saffron 已提交
3209 3210 3211
        /// <summary>
        /// Ansi vs Unicode 
        /// </summary>
M
mgravell 已提交
3212
        public bool IsAnsi { get; set; }
S
Sam Saffron 已提交
3213 3214 3215
        /// <summary>
        /// Fixed length 
        /// </summary>
M
mgravell 已提交
3216
        public bool IsFixedLength { get; set; }
S
Sam Saffron 已提交
3217 3218 3219
        /// <summary>
        /// Length of the string -1 for max
        /// </summary>
M
mgravell 已提交
3220
        public int Length { get; set; }
S
Sam Saffron 已提交
3221 3222 3223
        /// <summary>
        /// The value of the string
        /// </summary>
M
mgravell 已提交
3224
        public string Value { get; set; }
S
Sam Saffron 已提交
3225 3226 3227 3228 3229
        /// <summary>
        /// Add the parameter to the command... internal use only
        /// </summary>
        /// <param name="command"></param>
        /// <param name="name"></param>
M
mgravell 已提交
3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250
        public void AddParameter(IDbCommand command, string name)
        {
            if (IsFixedLength && Length == -1)
            {
                throw new InvalidOperationException("If specifying IsFixedLength,  a Length must also be specified");
            }
            var param = command.CreateParameter();
            param.ParameterName = name;
            param.Value = (object)Value ?? DBNull.Value;
            if (Length == -1 && Value != null && Value.Length <= 4000)
            {
                param.Size = 4000;
            }
            else
            {
                param.Size = Length;
            }
            param.DbType = IsAnsi ? (IsFixedLength ? DbType.AnsiStringFixedLength : DbType.AnsiString) : (IsFixedLength ? DbType.StringFixedLength : DbType.String);
            command.Parameters.Add(param);
        }
    }
3251

3252 3253 3254 3255 3256 3257 3258 3259 3260
    /// <summary>
    /// Handles variances in features per DBMS
    /// </summary>
    partial class FeatureSupport
    {
        /// <summary>
        /// Dictionary of supported features index by connection type name
        /// </summary>
        private static readonly Dictionary<string, FeatureSupport> FeatureList = new Dictionary<string, FeatureSupport>(StringComparer.InvariantCultureIgnoreCase) {
3261 3262 3263 3264
				{"sqlserverconnection", new FeatureSupport { Arrays = false}},
				{"npgsqlconnection", new FeatureSupport {Arrays = true}}
		};

3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279
        /// <summary>
        /// Gets the featureset based on the passed connection
        /// </summary>
        public static FeatureSupport Get(IDbConnection connection)
        {
            string name = connection.GetType().Name;
            FeatureSupport features;
            return FeatureList.TryGetValue(name, out features) ? features : FeatureList.Values.First();
        }

        /// <summary>
        /// True if the db supports array columns e.g. Postgresql
        /// </summary>
        public bool Arrays { get; set; }
    }
3280

3281 3282 3283
    /// <summary>
    /// Represents simple memeber map for one of target parameter or property or field to source DataReader column
    /// </summary>
3284
    sealed partial class SimpleMemberMap : SqlMapper.IMemberMap
3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397
    {
        private readonly string _columnName;
        private readonly PropertyInfo _property;
        private readonly FieldInfo _field;
        private readonly ParameterInfo _parameter;

        /// <summary>
        /// Creates instance for simple property mapping
        /// </summary>
        /// <param name="columnName">DataReader column name</param>
        /// <param name="property">Target property</param>
        public SimpleMemberMap(string columnName, PropertyInfo property)
        {
            if (columnName == null)
                throw new ArgumentNullException("columnName");

            if (property == null)
                throw new ArgumentNullException("property");

            _columnName = columnName;
            _property = property;
        }

        /// <summary>
        /// Creates instance for simple field mapping
        /// </summary>
        /// <param name="columnName">DataReader column name</param>
        /// <param name="field">Target property</param>
        public SimpleMemberMap(string columnName, FieldInfo field)
        {
            if (columnName == null)
                throw new ArgumentNullException("columnName");

            if (field == null)
                throw new ArgumentNullException("field");

            _columnName = columnName;
            _field = field;
        }

        /// <summary>
        /// Creates instance for simple constructor parameter mapping
        /// </summary>
        /// <param name="columnName">DataReader column name</param>
        /// <param name="parameter">Target constructor parameter</param>
        public SimpleMemberMap(string columnName, ParameterInfo parameter)
        {
            if (columnName == null)
                throw new ArgumentNullException("columnName");

            if (parameter == null)
                throw new ArgumentNullException("parameter");

            _columnName = columnName;
            _parameter = parameter;
        }

        /// <summary>
        /// DataReader column name
        /// </summary>
        public string ColumnName
        {
            get { return _columnName; }
        }

        /// <summary>
        /// Target member type
        /// </summary>
        public Type MemberType
        {
            get
            {
                if (_field != null)
                    return _field.FieldType;

                if (_property != null)
                    return _property.PropertyType;

                if (_parameter != null)
                    return _parameter.ParameterType;

                return null;
            }
        }

        /// <summary>
        /// Target property
        /// </summary>
        public PropertyInfo Property
        {
            get { return _property; }
        }

        /// <summary>
        /// Target field
        /// </summary>
        public FieldInfo Field
        {
            get { return _field; }
        }

        /// <summary>
        /// Target constructor parameter
        /// </summary>
        public ParameterInfo Parameter
        {
            get { return _parameter; }
        }
    }

    /// <summary>
    /// Represents default type mapping strategy used by Dapper
    /// </summary>
3398
    sealed partial class DefaultTypeMap : SqlMapper.ITypeMap
3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515
    {
        private readonly List<FieldInfo> _fields;
        private readonly List<PropertyInfo> _properties;
        private readonly Type _type;

        /// <summary>
        /// Creates default type map
        /// </summary>
        /// <param name="type">Entity type</param>
        public DefaultTypeMap(Type type)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            _fields = GetSettableFields(type);
            _properties = GetSettableProps(type);
            _type = type;
        }

        internal static MethodInfo GetPropertySetter(PropertyInfo propertyInfo, Type type)
        {
            return propertyInfo.DeclaringType == type ?
                propertyInfo.GetSetMethod(true) :
                propertyInfo.DeclaringType.GetProperty(propertyInfo.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetSetMethod(true);
        }

        internal static List<PropertyInfo> GetSettableProps(Type t)
        {
            return t
                  .GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                  .Where(p => GetPropertySetter(p, t) != null)
                  .ToList();
        }

        internal static List<FieldInfo> GetSettableFields(Type t)
        {
            return t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).ToList();
        }

        /// <summary>
        /// Finds best constructor
        /// </summary>
        /// <param name="names">DataReader column names</param>
        /// <param name="types">DataReader column types</param>
        /// <returns>Matching constructor or default one</returns>
        public ConstructorInfo FindConstructor(string[] names, Type[] types)
        {
            var constructors = _type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            foreach (ConstructorInfo ctor in constructors.OrderBy(c => c.IsPublic ? 0 : (c.IsPrivate ? 2 : 1)).ThenBy(c => c.GetParameters().Length))
            {
                ParameterInfo[] ctorParameters = ctor.GetParameters();
                if (ctorParameters.Length == 0)
                    return ctor;

                if (ctorParameters.Length != types.Length)
                    continue;

                int i = 0;
                for (; i < ctorParameters.Length; i++)
                {
                    if (!String.Equals(ctorParameters[i].Name, names[i], StringComparison.OrdinalIgnoreCase))
                        break;
                    if (types[i] == typeof(byte[]) && ctorParameters[i].ParameterType.FullName == SqlMapper.LinqBinary)
                        continue;
                    var unboxedType = Nullable.GetUnderlyingType(ctorParameters[i].ParameterType) ?? ctorParameters[i].ParameterType;
                    if (unboxedType != types[i]
                        && !(unboxedType.IsEnum && Enum.GetUnderlyingType(unboxedType) == types[i])
                        && !(unboxedType == typeof(char) && types[i] == typeof(string)))
                        break;
                }

                if (i == ctorParameters.Length)
                    return ctor;
            }

            return null;
        }

        /// <summary>
        /// Gets mapping for constructor parameter
        /// </summary>
        /// <param name="constructor">Constructor to resolve</param>
        /// <param name="columnName">DataReader column name</param>
        /// <returns>Mapping implementation</returns>
        public SqlMapper.IMemberMap GetConstructorParameter(ConstructorInfo constructor, string columnName)
        {
            var parameters = constructor.GetParameters();

            return new SimpleMemberMap(columnName, parameters.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.OrdinalIgnoreCase)));
        }

        /// <summary>
        /// Gets member mapping for column
        /// </summary>
        /// <param name="columnName">DataReader column name</param>
        /// <returns>Mapping implementation</returns>
        public SqlMapper.IMemberMap GetMember(string columnName)
        {
            var property = _properties.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.Ordinal))
               ?? _properties.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.OrdinalIgnoreCase));

            if (property != null)
                return new SimpleMemberMap(columnName, property);

            var field = _fields.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.Ordinal))
               ?? _fields.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.OrdinalIgnoreCase));

            if (field != null)
                return new SimpleMemberMap(columnName, field);

            return null;
        }
    }

    /// <summary>
    /// Implements custom property mapping by user provided criteria (usually presence of some custom attribute with column to member mapping)
    /// </summary>
3516
    sealed partial class CustomPropertyTypeMap : SqlMapper.ITypeMap
3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556
    {
        private readonly Type _type;
        private readonly Func<Type, string, PropertyInfo> _propertySelector;

        /// <summary>
        /// Creates custom property mapping
        /// </summary>
        /// <param name="type">Target entity type</param>
        /// <param name="propertySelector">Property selector based on target type and DataReader column name</param>
        public CustomPropertyTypeMap(Type type, Func<Type, string, PropertyInfo> propertySelector)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            if (propertySelector == null)
                throw new ArgumentNullException("propertySelector");

            _type = type;
            _propertySelector = propertySelector;
        }

        /// <summary>
        /// Always returns default constructor
        /// </summary>
        /// <param name="names">DataReader column names</param>
        /// <param name="types">DataReader column types</param>
        /// <returns>Default constructor</returns>
        public ConstructorInfo FindConstructor(string[] names, Type[] types)
        {
            return _type.GetConstructor(new Type[0]);
        }

        /// <summary>
        /// Not impelmeneted as far as default constructor used for all cases
        /// </summary>
        /// <param name="constructor"></param>
        /// <param name="columnName"></param>
        /// <returns></returns>
        public SqlMapper.IMemberMap GetConstructorParameter(ConstructorInfo constructor, string columnName)
        {
3557
            throw new NotSupportedException();
3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571
        }

        /// <summary>
        /// Returns property based on selector strategy
        /// </summary>
        /// <param name="columnName">DataReader column name</param>
        /// <returns>Poperty member map</returns>
        public SqlMapper.IMemberMap GetMember(string columnName)
        {
            var prop = _propertySelector(_type, columnName);
            return prop != null ? new SimpleMemberMap(columnName, prop) : null;
        }
    }

3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582
    // Define DAPPER_MAKE_PRIVATE if you reference Dapper by source
    // and you like to make the Dapper types private (in order to avoid
    // conflicts with other projects that also reference Dapper by source)
#if !DAPPER_MAKE_PRIVATE

    public partial class SqlMapper
    {
    }

    public partial class DynamicParameters
    {
3583

3584 3585 3586 3587
    }

    public partial class DbString
    {
3588

3589 3590 3591 3592
    }

    public partial class SimpleMemberMap
    {
3593

3594
    }
3595

3596 3597
    public partial class DefaultTypeMap
    {
3598

3599 3600 3601 3602
    }

    public partial class CustomPropertyTypeMap
    {
3603

3604 3605
    }

3606 3607 3608 3609
    public partial class FeatureSupport
    {

    }
3610 3611

#endif
3612 3613

}