SqlMapper.cs 225.3 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;
21
using System.Globalization;
22
using System.Linq.Expressions;
23

24
namespace Dapper
S
Sam Saffron 已提交
25
{
26 27
    [AssemblyNeutral, AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
    internal sealed class AssemblyNeutralAttribute : Attribute { }
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

    /// <summary>
    /// Additional state flags that control command behaviour
    /// </summary>
    [Flags]
    public enum CommandFlags
    {
        /// <summary>
        /// No additonal flags
        /// </summary>
        None = 0,
        /// <summary>
        /// Should data be buffered before returning?
        /// </summary>
        Buffered = 1,
        /// <summary>
        /// Can async queries be pipelined?
        /// </summary>
        Pipelined = 2,
47 48 49 50
        /// <summary>
        /// Should the plan cache be bypassed?
        /// </summary>
        NoCache = 4
51
    }
52 53 54
    /// <summary>
    /// Represents the key aspects of a sql operation
    /// </summary>
55
    public struct CommandDefinition
56
    {
57 58 59 60 61 62 63 64 65 66 67
        internal static CommandDefinition ForCallback(object parameters)
        {
            if(parameters is DynamicParameters)
            {
                return new CommandDefinition(parameters);
            }
            else
            {
                return default(CommandDefinition);
            }
        }
68 69 70 71 72
        private readonly string commandText;
        private readonly object parameters;
        private readonly IDbTransaction transaction;
        private readonly int? commandTimeout;
        private readonly CommandType? commandType;
73
        private readonly CommandFlags flags;
74 75


76
        internal void OnCompleted()
77
        {
78
            if (parameters is SqlMapper.IParameterCallbacks)
79
            {
80
                ((SqlMapper.IParameterCallbacks)parameters).OnCompleted();
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
        /// <summary>
        /// The command (sql or a stored-procedure name) to execute
        /// </summary>
        public string CommandText { get { return commandText; } }
        /// <summary>
        /// The parameters associated with the command
        /// </summary>
        public object Parameters { get { return parameters; } }
        /// <summary>
        /// The active transaction for the command
        /// </summary>
        public IDbTransaction Transaction { get { return transaction; } }
        /// <summary>
        /// The effective timeout for the command
        /// </summary>
        public int? CommandTimeout { get { return commandTimeout; } }
        /// <summary>
        /// The type of command that the command-text represents
        /// </summary>
        public CommandType? CommandType { get { return commandType; } }

        /// <summary>
        /// Should data be buffered before returning?
        /// </summary>
107 108
        public bool Buffered { get { return (flags & CommandFlags.Buffered) != 0; } }

109 110 111 112 113
        /// <summary>
        /// Should the plan for this query be cached?
        /// </summary>
        internal bool AddToCache {  get { return (flags & CommandFlags.NoCache) == 0; } }

114 115 116 117 118 119 120 121 122
        /// <summary>
        /// Additional state flags against this command
        /// </summary>
        public CommandFlags Flags {  get { return flags; } }

        /// <summary>
        /// Can async queries be pipelined?
        /// </summary>
        public bool Pipelined { get { return (flags & CommandFlags.Pipelined) != 0; } }
123 124 125 126 127 128

        /// <summary>
        /// Initialize the command definition
        /// </summary>
#if CSHARP30
        public CommandDefinition(string commandText, object parameters, IDbTransaction transaction, int? commandTimeout,
129
            CommandType? commandType, CommandFlags flags)
130 131
#else
        public CommandDefinition(string commandText, object parameters = null, IDbTransaction transaction = null, int? commandTimeout = null,
132
            CommandType? commandType = null, CommandFlags flags = CommandFlags.Buffered
133 134 135 136 137 138 139 140 141 142 143
#if ASYNC
            , CancellationToken cancellationToken = default(CancellationToken)
#endif
            )
#endif
        {
            this.commandText = commandText;
            this.parameters = parameters;
            this.transaction = transaction;
            this.commandTimeout = commandTimeout;
            this.commandType = commandType;
144
            this.flags = flags;
145 146 147 148 149
#if ASYNC
            this.cancellationToken = cancellationToken;
#endif
        }

150 151 152 153 154
        private CommandDefinition(object parameters) : this()
        {
            this.parameters = parameters;
        }

155 156 157 158 159 160 161 162
#if ASYNC
        private readonly CancellationToken cancellationToken;
        /// <summary>
        /// For asynchronous operations, the cancellation-token
        /// </summary>
        public CancellationToken CancellationToken { get { return cancellationToken; } }
#endif

163

164 165 166
        internal IDbCommand SetupCommand(IDbConnection cnn, Action<IDbCommand, object> paramReader)
        {
            var cmd = cnn.CreateCommand();
167 168
            var init = GetInit(cmd.GetType());
            if (init != null) init(cmd);
169 170 171 172 173 174 175 176 177 178 179 180 181 182
            if (transaction != null)
                cmd.Transaction = transaction;
            cmd.CommandText = commandText;
            if (commandTimeout.HasValue)
                cmd.CommandTimeout = commandTimeout.Value;
            if (commandType.HasValue)
                cmd.CommandType = commandType.Value;
            if (paramReader != null)
            {
                paramReader(cmd, parameters);
            }
            return cmd;
        }

183 184
        static SqlMapper.Link<Type, Action<IDbCommand>> commandInitCache;
        static Action<IDbCommand> GetInit(Type commandType)
185 186
        {
            if (commandType == null) return null; // GIGO
187 188
            Action<IDbCommand> action;
            if (SqlMapper.Link<Type, Action<IDbCommand>>.TryGet(commandInitCache, commandType, out action))
189 190 191
            {
                return action;
            }
192 193 194
            var bindByName = GetBasicPropertySetter(commandType, "BindByName", typeof(bool));
            var initialLongFetchSize = GetBasicPropertySetter(commandType, "InitialLONGFetchSize", typeof(int));

195
            action = null;
196
            if (bindByName != null || initialLongFetchSize != null)
197
            {
198
                var method = new DynamicMethod(commandType.Name + "_init", null, new Type[] { typeof(IDbCommand) });
199
                var il = method.GetILGenerator();
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216

                if (bindByName != null)
                {
                    // .BindByName = true
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Castclass, commandType);
                    il.Emit(OpCodes.Ldc_I4_1);
                    il.EmitCall(OpCodes.Callvirt, bindByName, null);
                }
                if (initialLongFetchSize != null)
                {
                    // .InitialLONGFetchSize = -1
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Castclass, commandType);
                    il.Emit(OpCodes.Ldc_I4_M1);
                    il.EmitCall(OpCodes.Callvirt, initialLongFetchSize, null);
                }
217
                il.Emit(OpCodes.Ret);
218
                action = (Action<IDbCommand>)method.CreateDelegate(typeof(Action<IDbCommand>));
219 220
            }
            // cache it            
221
            SqlMapper.Link<Type, Action<IDbCommand>>.TryAdd(ref commandInitCache, commandType, ref action);
222 223
            return action;
        }
224 225 226 227 228 229 230 231 232 233 234
        static MethodInfo GetBasicPropertySetter(Type declaringType, string name, Type expectedType)
        {
            var prop = declaringType.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
            ParameterInfo[] indexers;
            if (prop != null && prop.CanWrite && prop.PropertyType == expectedType
                && ((indexers = prop.GetIndexParameters()) == null || indexers.Length == 0))
            {
                return prop.GetSetMethod();
            }
            return null;
        }
235 236
    }

S
Sam Saffron 已提交
237 238 239
    /// <summary>
    /// Dapper, a light weight object mapper for ADO.NET
    /// </summary>
240
    static partial class SqlMapper
S
Sam Saffron 已提交
241
    {
S
Sam Saffron 已提交
242 243 244
        /// <summary>
        /// Implement this interface to pass an arbitrary db specific set of parameters to Dapper
        /// </summary>
245
        public partial interface IDynamicParameters
S
Sam Saffron 已提交
246
        {
S
Sam Saffron 已提交
247 248 249 250 251
            /// <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>
252
            void AddParameters(IDbCommand command, Identity identity);
S
Sam Saffron 已提交
253
        }
254

255 256 257 258 259 260 261 262 263 264 265
        /// <summary>
        /// Extends IDynamicParameters providing by-name lookup of parameter values
        /// </summary>
        public interface IParameterLookup : IDynamicParameters
        {
            /// <summary>
            /// Get the value of the specified parameter (return null if not found)
            /// </summary>
            object this[string name] { get; }
        }

266 267 268 269 270 271 272 273 274 275 276
        /// <summary>
        /// Extends IDynamicParameters with facitilies for executing callbacks after commands have completed
        /// </summary>
        public partial interface IParameterCallbacks : IDynamicParameters
        {
            /// <summary>
            /// Invoked when the command has executed
            /// </summary>
            void OnCompleted();
        }

277 278 279
        /// <summary>
        /// Implement this interface to pass an arbitrary db specific parameter to Dapper
        /// </summary>
280
        [AssemblyNeutral]
281 282 283 284 285 286 287 288 289 290
        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);
        }

291 292 293
        /// <summary>
        /// Implement this interface to perform custom type-based parameter handling and value parsing
        /// </summary>
294
        [AssemblyNeutral]
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
        public interface ITypeHandler
        {
            /// <summary>
            /// Assign the value of a parameter before a command executes
            /// </summary>
            /// <param name="parameter">The parameter to configure</param>
            /// <param name="value">Parameter value</param>
            void SetValue(IDbDataParameter parameter, object value);

            /// <summary>
            /// Parse a database value back to a typed value
            /// </summary>
            /// <param name="value">The value from the database</param>
            /// <param name="destinationType">The type to parse to</param>
            /// <returns>The typed value</returns>
            object Parse(Type destinationType, object value);
        }

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
        /// <summary>
        /// A type handler for data-types that are supported by the underlying provider, but which need
        /// a well-known UdtTypeName to be specified
        /// </summary>
        public class UdtTypeHandler : ITypeHandler
        {
            private readonly string udtTypeName;
            /// <summary>
            /// Creates a new instance of UdtTypeHandler with the specified UdtTypeName
            /// </summary>
            public UdtTypeHandler(string udtTypeName)
            {
                if (string.IsNullOrEmpty(udtTypeName)) throw new ArgumentException("Cannot be null or empty", udtTypeName);
                this.udtTypeName = udtTypeName;
            }
            object ITypeHandler.Parse(Type destinationType, object value)
            {
                return value is DBNull ? null : value;
            }

            void ITypeHandler.SetValue(IDbDataParameter parameter, object value)
            {
                parameter.Value = ((object)value) ?? DBNull.Value;
                if (parameter is System.Data.SqlClient.SqlParameter)
                {
                    ((System.Data.SqlClient.SqlParameter)parameter).UdtTypeName = udtTypeName;
                }
            }
        }

343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
        /// <summary>
        /// Base-class for simple type-handlers
        /// </summary>
        public abstract class TypeHandler<T> : ITypeHandler
        {
            /// <summary>
            /// Assign the value of a parameter before a command executes
            /// </summary>
            /// <param name="parameter">The parameter to configure</param>
            /// <param name="value">Parameter value</param>
            public abstract void SetValue(IDbDataParameter parameter, T value);

            /// <summary>
            /// Parse a database value back to a typed value
            /// </summary>
            /// <param name="value">The value from the database</param>
            /// <returns>The typed value</returns>
            public abstract T Parse(object value);

            void ITypeHandler.SetValue(IDbDataParameter parameter, object value)
            {
                if (value is DBNull)
                {
                    parameter.Value = value;
                }
                else
                {
                    SetValue(parameter, (T)value);
                }
            }

            object ITypeHandler.Parse(Type destinationType, object value)
            {
                return Parse(value);
            }
        }

380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
        /// <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 已提交
440 441 442 443 444
        /// <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>
445
        internal partial class Link<TKey, TValue> where TKey : class
M
mgravell 已提交
446 447 448 449 450
        {
            public static bool TryGet(Link<TKey, TValue> link, TKey key, out TValue value)
            {
                while (link != null)
                {
451
                    if ((object)key == (object)link.Key)
M
mgravell 已提交
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
                    {
                        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; }
        }
489
        partial class CacheInfo
S
Sam Saffron 已提交
490
        {
491
            public DeserializerState Deserializer { get; set; }
M
mgravell 已提交
492
            public Func<IDataReader, object>[] OtherDeserializers { get; set; }
493
            public Action<IDbCommand, object> ParamReader { get; set; }
M
mgravell 已提交
494 495 496
            private int hitCount;
            public int GetHitCount() { return Interlocked.CompareExchange(ref hitCount, 0, 0); }
            public void RecordHit() { Interlocked.Increment(ref hitCount); }
S
Sam Saffron 已提交
497
        }
498 499 500 501 502 503
        static int GetColumnHash(IDataReader reader)
        {
            unchecked
            {
                int colCount = reader.FieldCount, hash = colCount;
                for (int i = 0; i < colCount; i++)
504
                {   // binding code is only interested in names - not types
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
                    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;
            }
        }
522

S
Sam Saffron 已提交
523 524 525
        /// <summary>
        /// Called if the query cache is purged via PurgeQueryCache
        /// </summary>
526 527 528 529 530 531
        public static event EventHandler QueryCachePurged;
        private static void OnQueryCachePurged()
        {
            var handler = QueryCachePurged;
            if (handler != null) handler(null, EventArgs.Empty);
        }
M
mgravell 已提交
532 533
#if CSHARP30
        private static readonly Dictionary<Identity, CacheInfo> _queryCache = new Dictionary<Identity, CacheInfo>();
534 535
        // 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 已提交
536 537
        private static void SetQueryCache(Identity key, CacheInfo value)
        {
538
            lock (_queryCache) { _queryCache[key] = value; }
M
mgravell 已提交
539 540 541
        }
        private static bool TryGetQueryCache(Identity key, out CacheInfo value)
        {
542
            lock (_queryCache) { return _queryCache.TryGetValue(key, out value); }
M
mgravell 已提交
543
        }
544 545 546 547 548 549 550 551 552
        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 已提交
553 554 555
        /// <summary>
        /// Purge the query cache 
        /// </summary>
556 557 558 559
        public static void PurgeQueryCache()
        {
            lock (_queryCache)
            {
560
                _queryCache.Clear();
561 562
            }
            OnQueryCachePurged();
563
        }
M
mgravell 已提交
564 565 566 567
#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)
        {
568
            if (Interlocked.Increment(ref collect) == COLLECT_PER_ITEMS)
M
mgravell 已提交
569 570 571
            {
                CollectCacheGarbage();
            }
M
mgravell 已提交
572 573
            _queryCache[key] = value;
        }
M
mgravell 已提交
574 575 576 577 578 579 580 581 582 583 584 585 586 587

        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);
                    }
                }
            }
588

M
mgravell 已提交
589 590 591 592 593 594 595 596
            finally
            {
                Interlocked.Exchange(ref collect, 0);
            }
        }

        private const int COLLECT_PER_ITEMS = 1000, COLLECT_HIT_COUNT_MIN = 0;
        private static int collect;
M
mgravell 已提交
597 598
        private static bool TryGetQueryCache(Identity key, out CacheInfo value)
        {
599
            if (_queryCache.TryGetValue(key, out value))
M
mgravell 已提交
600 601 602 603 604 605
            {
                value.RecordHit();
                return true;
            }
            value = null;
            return false;
M
mgravell 已提交
606
        }
S
Sam Saffron 已提交
607

S
Sam Saffron 已提交
608 609 610
        /// <summary>
        /// Purge the query cache 
        /// </summary>
611 612 613 614
        public static void PurgeQueryCache()
        {
            _queryCache.Clear();
            OnQueryCachePurged();
615
        }
M
mgravell 已提交
616

617 618 619 620 621 622 623 624 625 626
        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 已提交
627 628 629 630
        /// <summary>
        /// Return a count of all the cached queries by dapper
        /// </summary>
        /// <returns></returns>
M
mgravell 已提交
631 632 633 634 635
        public static int GetCachedSQLCount()
        {
            return _queryCache.Count;
        }

S
Sam Saffron 已提交
636 637 638 639 640
        /// <summary>
        /// Return a list of all the queries cached by dapper
        /// </summary>
        /// <param name="ignoreHitCountAbove"></param>
        /// <returns></returns>
M
mgravell 已提交
641 642 643 644 645 646 647
        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 已提交
648 649 650 651
        /// <summary>
        /// Deep diagnostics only: find any hash collisions in the cache
        /// </summary>
        /// <returns></returns>
652
        public static IEnumerable<Tuple<int, int>> GetHashCollissions()
M
mgravell 已提交
653 654
        {
            var counts = new Dictionary<int, int>();
655
            foreach (var key in _queryCache.Keys)
M
mgravell 已提交
656 657
            {
                int count;
658
                if (!counts.TryGetValue(key.hashCode, out count))
M
mgravell 已提交
659 660
                {
                    counts.Add(key.hashCode, 1);
661 662
                }
                else
M
mgravell 已提交
663 664 665 666 667 668 669 670 671
                {
                    counts[key.hashCode] = count + 1;
                }
            }
            return from pair in counts
                   where pair.Value > 1
                   select Tuple.Create(pair.Key, pair.Value);

        }
M
mgravell 已提交
672
#endif
M
mgravell 已提交
673 674


M
Marc Gravell 已提交
675
        static Dictionary<Type, DbType> typeMap;
676

S
Sam Saffron 已提交
677 678
        static SqlMapper()
        {
M
mgravell 已提交
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
            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 已提交
697
            typeMap[typeof(TimeSpan)] = DbType.Time;
M
mgravell 已提交
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
            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 已提交
715
            typeMap[typeof(TimeSpan?)] = DbType.Time;
716
            typeMap[typeof(object)] = DbType.Object;
717

M
Marc Gravell 已提交
718
            AddTypeHandlerImpl(typeof(DataTable), new DataTableHandler(), false);
719
        }
720 721 722 723 724 725 726 727 728

        /// <summary>
        /// Clear the registered type handlers
        /// </summary>
        public static void ResetTypeHandlers()
        {
            typeHandlers = new Dictionary<Type, ITypeHandler>();
            AddTypeHandlerImpl(typeof(DataTable), new DataTableHandler(), true);
        }
729 730 731
        /// <summary>
        /// Configire the specified type to be mapped to a given db-type
        /// </summary>
732 733
        public static void AddTypeMap(Type type, DbType dbType)
        {
M
Marc Gravell 已提交
734 735 736 737 738 739 740 741 742
            // use clone, mutate, replace to avoid threading issues
            var snapshot = typeMap;

            DbType oldValue;
            if (snapshot.TryGetValue(type, out oldValue) && oldValue == dbType) return; // nothing to do

            var newCopy = new Dictionary<Type, DbType>(snapshot);
            newCopy[type] = dbType;
            typeMap = newCopy;
743 744
        }

745 746 747 748
        /// <summary>
        /// Configire the specified type to be processed by a custom handler
        /// </summary>
        public static void AddTypeHandler(Type type, ITypeHandler handler)
M
Marc Gravell 已提交
749 750 751 752 753 754 755 756
        {
            AddTypeHandlerImpl(type, handler, true);
        }

        /// <summary>
        /// Configire the specified type to be processed by a custom handler
        /// </summary>
        public static void AddTypeHandlerImpl(Type type, ITypeHandler handler, bool clone)
757 758
        {
            if (type == null) throw new ArgumentNullException("type");
M
Marc Gravell 已提交
759

760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
            Type secondary = null;
            if(type.IsValueType)
            {
                var underlying = Nullable.GetUnderlyingType(type);
                if(underlying == null)
                {
                    secondary = typeof(Nullable<>).MakeGenericType(type); // the Nullable<T>
                    // type is already the T
                }
                else
                {
                    secondary = type; // the Nullable<T>
                    type = underlying; // the T
                }
            }

M
Marc Gravell 已提交
776 777 778 779 780 781
            var snapshot = typeHandlers;
            ITypeHandler oldValue;
            if (snapshot.TryGetValue(type, out oldValue) && handler == oldValue) return; // nothing to do

            var newCopy = clone ? new Dictionary<Type, ITypeHandler>(snapshot) : snapshot;

782 783
#pragma warning disable 618
            typeof(TypeHandlerCache<>).MakeGenericType(type).GetMethod("SetHandler", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, new object[] { handler });
784 785 786 787
            if(secondary != null)
            {
                typeof(TypeHandlerCache<>).MakeGenericType(secondary).GetMethod("SetHandler", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, new object[] { handler });
            }
788
#pragma warning restore 618
789 790 791 792 793 794 795 796 797 798
            if (handler == null)
            {
                newCopy.Remove(type);
                if (secondary != null) newCopy.Remove(secondary);
            }
            else
            {
                newCopy[type] = handler;
                if(secondary != null) newCopy[secondary] = handler;
            }
M
Marc Gravell 已提交
799
            typeHandlers = newCopy;
800
        }
M
Marc Gravell 已提交
801

802 803 804 805 806
        /// <summary>
        /// Configire the specified type to be processed by a custom handler
        /// </summary>
        public static void AddTypeHandler<T>(TypeHandler<T> handler)
        {
M
Marc Gravell 已提交
807
            AddTypeHandlerImpl(typeof(T), handler, true);
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
        }

        /// <summary>
        /// Not intended for direct usage
        /// </summary>
        [Obsolete("Not intended for direct usage", false)]
        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        public static class TypeHandlerCache<T>
        {
            /// <summary>
            /// Not intended for direct usage
            /// </summary>
            [Obsolete("Not intended for direct usage", true)]
            public static T Parse(object value)
            {
                return (T)handler.Parse(typeof(T), value);
                
            }

            /// <summary>
            /// Not intended for direct usage
            /// </summary>
            [Obsolete("Not intended for direct usage", true)]
            public static void SetValue(IDbDataParameter parameter, object value)
            {
                handler.SetValue(parameter, value);
            }

            internal static void SetHandler(ITypeHandler handler)
            {
#pragma warning disable 618
                TypeHandlerCache<T>.handler = handler;
#pragma warning restore 618
            }

            private static ITypeHandler handler;
        }

M
Marc Gravell 已提交
846
        private static Dictionary<Type, ITypeHandler> typeHandlers = new Dictionary<Type, ITypeHandler>();
847

848
        internal const string LinqBinary = "System.Data.Linq.Binary";
849
        internal static DbType LookupDbType(Type type, string name, out ITypeHandler handler)
850
        {
851
            DbType dbType;
852
            handler = null;
853 854
            var nullUnderlyingType = Nullable.GetUnderlyingType(type);
            if (nullUnderlyingType != null) type = nullUnderlyingType;
855
            if (type.IsEnum && !typeMap.ContainsKey(type))
856 857 858
            {
                type = Enum.GetUnderlyingType(type);
            }
M
mgravell 已提交
859
            if (typeMap.TryGetValue(type, out dbType))
860 861 862
            {
                return dbType;
            }
M
mgravell 已提交
863 864 865 866
            if (type.FullName == LinqBinary)
            {
                return DbType.Binary;
            }
867
            if (typeof(IEnumerable).IsAssignableFrom(type))
868
            {
869
                return DynamicParameters.EnumerableMultiParameter;
870 871
            }

872 873 874 875
            if (typeHandlers.TryGetValue(type, out handler))
            {
                return DbType.Object;
            }
876 877 878 879 880 881 882 883
            switch (type.FullName)
            {
                case "Microsoft.SqlServer.Types.SqlGeography":
                    AddTypeHandler(type, handler = new UdtTypeHandler("GEOGRAPHY"));
                    return DbType.Object;
                case "Microsoft.SqlServer.Types.SqlGeometry":
                    AddTypeHandler(type, handler = new UdtTypeHandler("GEOMETRY"));
                    return DbType.Object;
884 885 886
                case "Microsoft.SqlServer.Types.SqlHierarchyId":
                    AddTypeHandler(type, handler = new UdtTypeHandler("HIERARCHYID"));
                    return DbType.Object;
887 888
            }
            throw new NotSupportedException(string.Format("The member {0} of type {1} cannot be used as a parameter value", name, type));
S
Sam Saffron 已提交
889 890
        }

S
Sam Saffron 已提交
891 892 893
        /// <summary>
        /// Identity of a cached query in Dapper, used for extensability
        /// </summary>
894
        public partial class Identity : IEquatable<Identity>
S
Sam Saffron 已提交
895
        {
896 897
            internal Identity ForGrid(Type primaryType, int gridIndex)
            {
898
                return new Identity(sql, commandType, connectionString, primaryType, parametersType, null, gridIndex);
899
            }
900 901 902

            internal Identity ForGrid(Type primaryType, Type[] otherTypes, int gridIndex)
            {
903
                return new Identity(sql, commandType, connectionString, primaryType, parametersType, otherTypes, gridIndex);
904
            }
S
Sam Saffron 已提交
905 906 907 908 909
            /// <summary>
            /// Create an identity for use with DynamicParameters, internal use only
            /// </summary>
            /// <param name="type"></param>
            /// <returns></returns>
910 911
            public Identity ForDynamicParameters(Type type)
            {
912
                return new Identity(sql, commandType, connectionString, this.type, type, null, -1);
913 914
            }

915 916
            internal Identity(string sql, CommandType? commandType, IDbConnection connection, Type type, Type parametersType, Type[] otherTypes)
                : this(sql, commandType, connection.ConnectionString, type, parametersType, otherTypes, 0)
917
            { }
918
            private Identity(string sql, CommandType? commandType, string connectionString, Type type, Type parametersType, Type[] otherTypes, int gridIndex)
S
Sam Saffron 已提交
919 920
            {
                this.sql = sql;
921
                this.commandType = commandType;
922
                this.connectionString = connectionString;
S
Sam Saffron 已提交
923
                this.type = type;
S
Sam Saffron 已提交
924
                this.parametersType = parametersType;
925
                this.gridIndex = gridIndex;
M
mgravell 已提交
926 927 928
                unchecked
                {
                    hashCode = 17; // we *know* we are using this in a dictionary, so pre-compute this
929
                    hashCode = hashCode * 23 + commandType.GetHashCode();
930
                    hashCode = hashCode * 23 + gridIndex.GetHashCode();
M
mgravell 已提交
931 932
                    hashCode = hashCode * 23 + (sql == null ? 0 : sql.GetHashCode());
                    hashCode = hashCode * 23 + (type == null ? 0 : type.GetHashCode());
S
Sam Saffron 已提交
933 934
                    if (otherTypes != null)
                    {
935
                        foreach (var t in otherTypes)
S
Sam Saffron 已提交
936
                        {
937
                            hashCode = hashCode * 23 + (t == null ? 0 : t.GetHashCode());
S
Sam Saffron 已提交
938 939
                        }
                    }
940
                    hashCode = hashCode * 23 + (connectionString == null ? 0 : SqlMapper.connectionStringComparer.GetHashCode(connectionString));
S
Sam Saffron 已提交
941
                    hashCode = hashCode * 23 + (parametersType == null ? 0 : parametersType.GetHashCode());
M
mgravell 已提交
942
                }
S
Sam Saffron 已提交
943
            }
944

S
Sam Saffron 已提交
945 946 947 948 949
            /// <summary>
            /// 
            /// </summary>
            /// <param name="obj"></param>
            /// <returns></returns>
S
Sam Saffron 已提交
950 951 952 953
            public override bool Equals(object obj)
            {
                return Equals(obj as Identity);
            }
S
Sam Saffron 已提交
954 955 956
            /// <summary>
            /// The sql
            /// </summary>
957
            public readonly string sql;
S
Sam Saffron 已提交
958 959 960
            /// <summary>
            /// The command type 
            /// </summary>
961
            public readonly CommandType? commandType;
962

S
Sam Saffron 已提交
963 964 965
            /// <summary>
            /// 
            /// </summary>
966
            public readonly int hashCode, gridIndex;
967 968 969 970
            /// <summary>
            /// 
            /// </summary>
            public readonly Type type;
S
Sam Saffron 已提交
971 972 973
            /// <summary>
            /// 
            /// </summary>
974
            public readonly string connectionString;
S
Sam Saffron 已提交
975 976 977
            /// <summary>
            /// 
            /// </summary>
978
            public readonly Type parametersType;
S
Sam Saffron 已提交
979 980 981 982
            /// <summary>
            /// 
            /// </summary>
            /// <returns></returns>
S
Sam Saffron 已提交
983 984 985 986
            public override int GetHashCode()
            {
                return hashCode;
            }
S
Sam Saffron 已提交
987 988 989 990 991
            /// <summary>
            /// Compare 2 Identity objects
            /// </summary>
            /// <param name="other"></param>
            /// <returns></returns>
S
Sam Saffron 已提交
992 993
            public bool Equals(Identity other)
            {
994
                return
995 996
                    other != null &&
                    gridIndex == other.gridIndex &&
997 998
                    type == other.type &&
                    sql == other.sql &&
999
                    commandType == other.commandType &&
1000
                    SqlMapper.connectionStringComparer.Equals(connectionString, other.connectionString) &&
S
Sam Saffron 已提交
1001
                    parametersType == other.parametersType;
S
Sam Saffron 已提交
1002 1003 1004
            }
        }

M
mgravell 已提交
1005 1006 1007 1008 1009 1010 1011 1012 1013
#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);
        }
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041

        /// <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);
        }

J
JJoe2 已提交
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
        /// <summary>
        /// Execute parameterized SQL and return an <see cref="IDataReader"/>
        /// </summary>
        /// <returns>An <see cref="IDataReader"/> that can be used to iterate over the results of the SQL query.</returns>
        public static IDataReader ExecuteReader(this IDbConnection cnn, string sql, object param)
        {
            return ExecuteReader(cnn, sql, param, null, null, null);
        }

        /// <summary>
        /// Execute parameterized SQL and return an <see cref="IDataReader"/>
        /// </summary>
        /// <returns>An <see cref="IDataReader"/> that can be used to iterate over the results of the SQL query.</returns>
        public static IDataReader ExecuteReader(this IDbConnection cnn, string sql, object param, IDbTransaction transaction)
        {
            return ExecuteReader(cnn, sql, param, transaction, null, null);
        }

        /// <summary>
        /// Execute parameterized SQL and return an <see cref="IDataReader"/>
        /// </summary>
        /// <returns>An <see cref="IDataReader"/> that can be used to iterate over the results of the SQL query.</returns>
        public static IDataReader ExecuteReader(this IDbConnection cnn, string sql, object param, CommandType commandType)
        {
            return ExecuteReader(cnn, sql, param, null, null, commandType);
        }

        /// <summary>
        /// Execute parameterized SQL and return an <see cref="IDataReader"/>
        /// </summary>
        /// <returns>An <see cref="IDataReader"/> that can be used to iterate over the results of the SQL query.</returns>
        public static IDataReader ExecuteReader(this IDbConnection cnn, string sql, object param, IDbTransaction transaction, CommandType commandType)
        {
            return ExecuteReader(cnn, sql, param, transaction, null, commandType);
        }

M
mgravell 已提交
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
        /// <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);
        }

1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
        /// <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 已提交
1122 1123 1124
        /// <summary>
        /// Execute a command that returns multiple result sets, and access each in turn
        /// </summary>
1125
        public static GridReader QueryMultiple(this IDbConnection cnn, string sql, object param, IDbTransaction transaction)
J
Joao Silva 已提交
1126 1127 1128 1129 1130 1131 1132
        {
            return QueryMultiple(cnn, sql, param, transaction, null, null);
        }

        /// <summary>
        /// Execute a command that returns multiple result sets, and access each in turn
        /// </summary>
1133
        public static GridReader QueryMultiple(this IDbConnection cnn, string sql, object param, CommandType commandType)
J
Joao Silva 已提交
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
        {
            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 已提交
1145
#endif
J
JJoe2 已提交
1146 1147


S
Sam Saffron 已提交
1148 1149 1150 1151
        /// <summary>
        /// Execute parameterized SQL  
        /// </summary>
        /// <returns>Number of rows affected</returns>
M
mgravell 已提交
1152 1153
        public static int Execute(
#if CSHARP30
1154
this IDbConnection cnn, string sql, object param, IDbTransaction transaction, int? commandTimeout, CommandType? commandType
M
mgravell 已提交
1155
#else
1156
this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null
M
mgravell 已提交
1157 1158 1159
#endif
)
        {
1160
            var command = new CommandDefinition(sql, (object)param, transaction, commandTimeout, commandType, CommandFlags.Buffered);
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
            return ExecuteImpl(cnn, ref command);
        }
        /// <summary>
        /// Execute parameterized SQL  
        /// </summary>
        /// <returns>Number of rows affected</returns>
        public static int Execute(this IDbConnection cnn, CommandDefinition command)
        {
            return ExecuteImpl(cnn, ref command);
        }
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180


        /// <summary>
        /// Execute parameterized SQL that selects a single value
        /// </summary>
        /// <returns>The first cell selected</returns>
        public static object ExecuteScalar(
#if CSHARP30
this IDbConnection cnn, string sql, object param, IDbTransaction transaction, int? commandTimeout, CommandType? commandType
#else
1181
this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
#endif
)
        {
            var command = new CommandDefinition(sql, (object)param, transaction, commandTimeout, commandType, CommandFlags.Buffered);
            return ExecuteScalarImpl<object>(cnn, ref command);
        }

        /// <summary>
        /// Execute parameterized SQL that selects a single value
        /// </summary>
        /// <returns>The first cell selected</returns>
        public static T ExecuteScalar<T>(
#if CSHARP30
this IDbConnection cnn, string sql, object param, IDbTransaction transaction, int? commandTimeout, CommandType? commandType
#else
1197
this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
#endif
)
        {
            var command = new CommandDefinition(sql, (object)param, transaction, commandTimeout, commandType, CommandFlags.Buffered);
            return ExecuteScalarImpl<T>(cnn, ref command);
        }

        /// <summary>
        /// Execute parameterized SQL that selects a single value
        /// </summary>
        /// <returns>The first cell selected</returns>
        public static object ExecuteScalar(this IDbConnection cnn, CommandDefinition command)
        {
            return ExecuteScalarImpl<object>(cnn, ref command);
        }

        /// <summary>
        /// Execute parameterized SQL that selects a single value
        /// </summary>
        /// <returns>The first cell selected</returns>
        public static T ExecuteScalar<T>(this IDbConnection cnn, CommandDefinition command)
        {
            return ExecuteScalarImpl<T>(cnn, ref command);
        }

1223 1224 1225 1226
        private static int ExecuteImpl(this IDbConnection cnn, ref CommandDefinition command)
        {
            object param = command.Parameters;
            IEnumerable multiExec = param as IEnumerable;
1227
            Identity identity;
1228
            CacheInfo info = null;
1229
            if (multiExec != null && !(multiExec is string))
1230
            {
1231 1232 1233 1234 1235 1236 1237
#if ASYNC
                if((command.Flags & CommandFlags.Pipelined) != 0)
                {
                    // this includes all the code for concurrent/overlapped query
                    return ExecuteMultiImplAsync(cnn, command, multiExec).Result;
                }
#endif
1238 1239
                bool isFirst = true;
                int total = 0;
1240 1241
                bool wasClosed = cnn.State == ConnectionState.Closed;
                try
1242
                {
1243 1244
                    if (wasClosed) cnn.Open();
                    using (var cmd = command.SetupCommand(cnn, null))
1245
                    {
1246 1247
                        string masterSql = null;
                        foreach (var obj in multiExec)
1248
                        {
1249 1250 1251 1252 1253
                            if (isFirst)
                            {
                                masterSql = cmd.CommandText;
                                isFirst = false;
                                identity = new Identity(command.CommandText, cmd.CommandType, cnn, null, obj.GetType(), null);
1254
                                info = GetCacheInfo(identity, obj, command.AddToCache);
1255 1256 1257 1258 1259 1260 1261 1262
                            }
                            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();
1263
                        }
1264
                    }
1265
                    command.OnCompleted();
1266 1267 1268
                } finally
                {
                    if (wasClosed) cnn.Close();
1269
                }
1270
                return total;
1271 1272 1273
            }

            // nice and simple
1274
            if (param != null)
M
mgravell 已提交
1275
            {
1276
                identity = new Identity(command.CommandText, command.CommandType, cnn, null, param.GetType(), null);
1277
                info = GetCacheInfo(identity, param, command.AddToCache);
M
mgravell 已提交
1278
            }
1279
            return ExecuteCommand(cnn, ref command, param == null ? null : info.ParamReader);
S
Sam Saffron 已提交
1280
        }
J
JJoe2 已提交
1281 1282 1283 1284 1285 1286 1287 1288

        /// <summary>
        /// Execute parameterized SQL and return an <see cref="IDataReader"/>
        /// </summary>
        /// <returns>An <see cref="IDataReader"/> that can be used to iterate over the results of the SQL query.</returns>
        /// <remarks>
        /// This is typically used when the results of a query are not processed by Dapper, for example, used to fill a <see cref="DataTable"/>
        /// or <see cref="DataSet"/>.
1289
        /// </remarks>
J
JJoe2 已提交
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
        /// <example>
        /// <code>
        /// <![CDATA[
        /// DataTable table = new DataTable("MyTable");
        /// using (var reader = ExecuteReader(cnn, sql, param))
        /// {
        ///     table.Load(reader);
        /// }
        /// ]]>
        /// </code>
        /// </example>
        public static IDataReader ExecuteReader(
#if CSHARP30
this IDbConnection cnn, string sql, object param, IDbTransaction transaction, int? commandTimeout, CommandType? commandType
#else
1305
this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null
J
JJoe2 已提交
1306 1307 1308
#endif
)
        {
1309
            var command = new CommandDefinition(sql, (object)param, transaction, commandTimeout, commandType, CommandFlags.Buffered);
M
Marc Gravell 已提交
1310
            return ExecuteReaderImpl(cnn, ref command, CommandBehavior.Default);
1311
        }
J
JJoe2 已提交
1312

1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
        /// <summary>
        /// Execute parameterized SQL and return an <see cref="IDataReader"/>
        /// </summary>
        /// <returns>An <see cref="IDataReader"/> that can be used to iterate over the results of the SQL query.</returns>
        /// <remarks>
        /// This is typically used when the results of a query are not processed by Dapper, for example, used to fill a <see cref="DataTable"/>
        /// or <see cref="DataSet"/>.
        /// </remarks>
        public static IDataReader ExecuteReader(this IDbConnection cnn, CommandDefinition command)
        {
M
Marc Gravell 已提交
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
            return ExecuteReaderImpl(cnn, ref command, CommandBehavior.Default);
        }
        /// <summary>
        /// Execute parameterized SQL and return an <see cref="IDataReader"/>
        /// </summary>
        /// <returns>An <see cref="IDataReader"/> that can be used to iterate over the results of the SQL query.</returns>
        /// <remarks>
        /// This is typically used when the results of a query are not processed by Dapper, for example, used to fill a <see cref="DataTable"/>
        /// or <see cref="DataSet"/>.
        /// </remarks>
        public static IDataReader ExecuteReader(this IDbConnection cnn, CommandDefinition command, CommandBehavior commandBehavior)
        {
            return ExecuteReaderImpl(cnn, ref command, commandBehavior);
J
JJoe2 已提交
1336 1337
        }

M
mgravell 已提交
1338
#if !CSHARP30
1339
        /// <summary>
1340
        /// Return a list of dynamic objects, reader is closed after the call
1341
        /// </summary>
1342
        public static IEnumerable<dynamic> Query(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
1343
        {
1344
            return Query<DapperRow>(cnn, sql, param as object, transaction, buffered, commandTimeout, commandType);
S
Sam Saffron 已提交
1345
        }
1346 1347 1348 1349
#else
        /// <summary>
        /// Return a list of dynamic objects, reader is closed after the call
        /// </summary>
1350 1351
        public static IEnumerable<IDictionary<string, object>> Query(this IDbConnection cnn, string sql, object param)
        {
1352 1353 1354 1355 1356 1357
            return Query(cnn, sql, param, null, true, null, null);
        }

        /// <summary>
        /// Return a list of dynamic objects, reader is closed after the call
        /// </summary>
1358 1359
        public static IEnumerable<IDictionary<string, object>> Query(this IDbConnection cnn, string sql, object param, IDbTransaction transaction)
        {
1360 1361 1362 1363 1364 1365
            return Query(cnn, sql, param, transaction, true, null, null);
        }

        /// <summary>
        /// Return a list of dynamic objects, reader is closed after the call
        /// </summary>
1366 1367
        public static IEnumerable<IDictionary<string, object>> Query(this IDbConnection cnn, string sql, object param, CommandType? commandType)
        {
1368 1369 1370 1371 1372 1373
            return Query(cnn, sql, param, null, true, null, commandType);
        }

        /// <summary>
        /// Return a list of dynamic objects, reader is closed after the call
        /// </summary>
1374 1375
        public static IEnumerable<IDictionary<string, object>> Query(this IDbConnection cnn, string sql, object param, IDbTransaction transaction, CommandType? commandType)
        {
1376 1377 1378 1379 1380 1381
            return Query(cnn, sql, param, transaction, true, null, commandType);
        }

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

M
mgravell 已提交
1388 1389 1390
        /// <summary>
        /// Executes a query, returning the data typed as per T
        /// </summary>
S
Sam Saffron 已提交
1391
        /// <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 已提交
1392 1393 1394
        /// <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 已提交
1395 1396
        public static IEnumerable<T> Query<T>(
#if CSHARP30
1397
this IDbConnection cnn, string sql, object param, IDbTransaction transaction, bool buffered, int? commandTimeout, CommandType? commandType
M
mgravell 已提交
1398
#else
1399
this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null
M
mgravell 已提交
1400
#endif
1401
)
S
Sam Saffron 已提交
1402
        {
1403
            var command = new CommandDefinition(sql, (object)param, transaction, commandTimeout, commandType, buffered ? CommandFlags.Buffered : CommandFlags.None);
1404
            var data = QueryImpl<T>(cnn, command, typeof(T));
1405
            return command.Buffered ? data.ToList() : data;
1406 1407
        }

1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
        /// <summary>
        /// Executes a query, returning the data typed as per the Type suggested
        /// </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<object> Query(
#if CSHARP30
this IDbConnection cnn, Type type, string sql, object param, IDbTransaction transaction, bool buffered, int? commandTimeout, CommandType? commandType
#else
this IDbConnection cnn, Type type, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null
#endif
        )
        {
            if (type == null) throw new ArgumentNullException("type");
            var command = new CommandDefinition(sql, (object)param, transaction, commandTimeout, commandType, buffered ? CommandFlags.Buffered : CommandFlags.None);
            var data = QueryImpl<object>(cnn, command, type);
            return command.Buffered ? data.ToList() : data;
        }
1427 1428 1429 1430 1431 1432 1433 1434 1435
        /// <summary>
        /// Executes a query, returning the data typed as per T
        /// </summary>
        /// <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>
        /// <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, CommandDefinition command)
        {
1436
            var data = QueryImpl<T>(cnn, command, typeof(T));
1437 1438 1439 1440 1441
            return command.Buffered ? data.ToList() : data;
        }



M
mgravell 已提交
1442 1443 1444
        /// <summary>
        /// Execute a command that returns multiple result sets, and access each in turn
        /// </summary>
M
mgravell 已提交
1445
        public static GridReader QueryMultiple(
1446 1447
#if CSHARP30
this IDbConnection cnn, string sql, object param, IDbTransaction transaction, int? commandTimeout, CommandType? commandType
M
mgravell 已提交
1448
#else
1449
            this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null
M
mgravell 已提交
1450
#endif
1451
)
M
mgravell 已提交
1452
        {
1453
            var command = new CommandDefinition(sql, (object)param, transaction, commandTimeout, commandType, CommandFlags.Buffered);
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
            return QueryMultipleImpl(cnn, ref command);
        }
        /// <summary>
        /// Execute a command that returns multiple result sets, and access each in turn
        /// </summary>
        public static GridReader QueryMultiple(this IDbConnection cnn, CommandDefinition command)
        {
            return QueryMultipleImpl(cnn, ref command);
        }
        private static GridReader QueryMultipleImpl(this IDbConnection cnn, ref CommandDefinition command)
        {
            object param = command.Parameters;
            Identity identity = new Identity(command.CommandText, command.CommandType, cnn, typeof(GridReader), param == null ? null : param.GetType(), null);
1467
            CacheInfo info = GetCacheInfo(identity, param, command.AddToCache);
M
mgravell 已提交
1468 1469 1470

            IDbCommand cmd = null;
            IDataReader reader = null;
1471
            bool wasClosed = cnn.State == ConnectionState.Closed;
M
mgravell 已提交
1472 1473
            try
            {
1474
                if (wasClosed) cnn.Open();
1475
                cmd = command.SetupCommand(cnn, info.ParamReader);
M
Marc Gravell 已提交
1476
                reader = cmd.ExecuteReader(wasClosed ? CommandBehavior.CloseConnection | CommandBehavior.SequentialAccess : CommandBehavior.SequentialAccess);
1477

1478
                var result = new GridReader(cmd, reader, identity, command.Parameters as DynamicParameters);
1479
                wasClosed = false; // *if* the connection was closed and we got this far, then we now have a reader
1480 1481 1482 1483
                // 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 已提交
1484 1485 1486
            }
            catch
            {
1487 1488 1489
                if (reader != null)
                {
                    if (!reader.IsClosed) try { cmd.Cancel(); }
1490
                        catch { /* don't spoil the existing exception */ }
1491 1492
                    reader.Dispose();
                }
M
mgravell 已提交
1493
                if (cmd != null) cmd.Dispose();
1494
                if (wasClosed) cnn.Close();
M
mgravell 已提交
1495 1496 1497 1498
                throw;
            }
        }

1499
        private static IEnumerable<T> QueryImpl<T>(this IDbConnection cnn, CommandDefinition command, Type effectiveType)
1500
        {
1501
            object param = command.Parameters;
1502
            var identity = new Identity(command.CommandText, command.CommandType, cnn, effectiveType, param == null ? null : param.GetType(), null);
1503
            var info = GetCacheInfo(identity, param, command.AddToCache);
S
Sam Saffron 已提交
1504

1505 1506 1507 1508 1509
            IDbCommand cmd = null;
            IDataReader reader = null;

            bool wasClosed = cnn.State == ConnectionState.Closed;
            try
S
Sam Saffron 已提交
1510
            {
1511
                cmd = command.SetupCommand(cnn, info.ParamReader);
1512

1513
                if (wasClosed) cnn.Open();
M
Marc Gravell 已提交
1514
                reader = cmd.ExecuteReader(wasClosed ? CommandBehavior.CloseConnection | CommandBehavior.SequentialAccess : CommandBehavior.SequentialAccess);
1515
                wasClosed = false; // *if* the connection was closed and we got this far, then we now have a reader
1516 1517 1518
                // 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
1519 1520 1521
                var tuple = info.Deserializer;
                int hash = GetColumnHash(reader);
                if (tuple.Func == null || tuple.Hash != hash)
1522
                {
1523 1524
                    if (reader.FieldCount == 0) //https://code.google.com/p/dapper-dot-net/issues/detail?id=57
                        yield break;
1525
                    tuple = info.Deserializer = new DeserializerState(hash, GetDeserializer(effectiveType, reader, 0, -1, false));
1526
                    if(command.AddToCache) SetQueryCache(identity, info);
1527
                }
S
Sam Saffron 已提交
1528

1529
                var func = tuple.Func;
1530
                var convertToType = Nullable.GetUnderlyingType(effectiveType) ?? effectiveType;
1531 1532
                while (reader.Read())
                {
1533
                    object val = func(reader);
1534
					if (val == null || val is T) {
1535 1536
                        yield return (T)val;
                    } else {
1537
                        yield return (T)Convert.ChangeType(val, convertToType, CultureInfo.InvariantCulture);
1538
                    }
1539
                }
1540
                while (reader.NextResult()) { }
1541 1542 1543 1544
                // happy path; close the reader cleanly - no
                // need for "Cancel" etc
                reader.Dispose();
                reader = null;
1545

1546
                command.OnCompleted();
1547 1548 1549 1550
            }
            finally
            {
                if (reader != null)
1551
                {
1552
                    if (!reader.IsClosed) try { cmd.Cancel(); }
1553
                        catch { /* don't spoil the existing exception */ }
1554
                    reader.Dispose();
1555
                }
1556 1557
                if (wasClosed) cnn.Close();
                if (cmd != null) cmd.Dispose();
S
Sam Saffron 已提交
1558
            }
S
Sam Saffron 已提交
1559
        }
1560

S
Sam Saffron 已提交
1561
        /// <summary>
S
Sam Saffron 已提交
1562
        /// Maps a query to objects
S
Sam Saffron 已提交
1563
        /// </summary>
S
Sam Saffron 已提交
1564 1565 1566
        /// <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 已提交
1567 1568 1569 1570 1571
        /// <param name="cnn"></param>
        /// <param name="sql"></param>
        /// <param name="map"></param>
        /// <param name="param"></param>
        /// <param name="transaction"></param>
1572
        /// <param name="buffered"></param>
S
Sam Saffron 已提交
1573
        /// <param name="splitOn">The Field we should split and read the second object from (default: id)</param>
1574
        /// <param name="commandTimeout">Number of seconds before command execution timeout</param>
S
Sam Saffron 已提交
1575
        /// <param name="commandType">Is it a stored proc or a batch?</param>
S
Sam Saffron 已提交
1576
        /// <returns></returns>
M
mgravell 已提交
1577
        public static IEnumerable<TReturn> Query<TFirst, TSecond, TReturn>(
1578 1579
#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 已提交
1580
#else
1581
this IDbConnection cnn, string sql, Func<TFirst, TSecond, TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null
M
mgravell 已提交
1582
#endif
1583
)
S
Sam Saffron 已提交
1584
        {
1585
            return MultiMap<TFirst, TSecond, DontMap, DontMap, DontMap, DontMap, DontMap, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
S
Sam Saffron 已提交
1586 1587
        }

S
Sam Saffron 已提交
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
        /// <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 已提交
1605 1606
        public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TReturn>(
#if CSHARP30
1607
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 已提交
1608
#else
1609
this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null
M
mgravell 已提交
1610
#endif
1611
)
S
Sam Saffron 已提交
1612
        {
1613
            return MultiMap<TFirst, TSecond, TThird, DontMap, DontMap, DontMap, DontMap, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
S
Sam Saffron 已提交
1614 1615
        }

S
Sam Saffron 已提交
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
        /// <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 已提交
1634 1635
        public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TReturn>(
#if CSHARP30
1636
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 已提交
1637
#else
1638
this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null
M
mgravell 已提交
1639
#endif
1640
)
S
Sam Saffron 已提交
1641
        {
1642
            return MultiMap<TFirst, TSecond, TThird, TFourth, DontMap, DontMap, DontMap, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
S
Sam Saffron 已提交
1643
        }
1644

M
mgravell 已提交
1645
#if !CSHARP30
S
Sam Saffron 已提交
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
        /// <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>
1665
        public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(
1666
            this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
)
        {
            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>(
1693
            this IDbConnection cnn, string sql, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn> map, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null
1694
)
S
Sam Saffron 已提交
1695
        {
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720
            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>
1721
        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, object param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null)
1722 1723
        {
            return MultiMap<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(cnn, sql, map, param as object, transaction, buffered, splitOn, commandTimeout, commandType);
S
Sam Saffron 已提交
1724
        }
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743

        /// <summary>
        /// Perform a multi mapping query with arbitrary input parameters
        /// </summary>
        /// <typeparam name="TReturn">The return type</typeparam>
        /// <param name="cnn"></param>
        /// <param name="sql"></param>
        /// <param name="types">array of types in the recordset</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">Is it a stored proc or a batch?</param>
        /// <returns></returns>
        public static IEnumerable<TReturn> Query<TReturn>(this IDbConnection cnn, string sql, Type[] types, Func<object[], TReturn> map, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null)
        {
            var command = new CommandDefinition(sql, (object)param, transaction, commandTimeout, commandType, buffered ? CommandFlags.Buffered : CommandFlags.None);
1744
            var results = MultiMapImpl<TReturn>(cnn, command, types, map, splitOn, null, null, true);
1745 1746
            return buffered ? results.ToList() : results;
        }
M
mgravell 已提交
1747
#endif
1748
        partial class DontMap { }
1749
        static IEnumerable<TReturn> MultiMap<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(
1750
            this IDbConnection cnn, string sql, Delegate map, object param, IDbTransaction transaction, bool buffered, string splitOn, int? commandTimeout, CommandType? commandType)
S
Sam Saffron 已提交
1751
        {
1752
            var command = new CommandDefinition(sql, (object)param, transaction, commandTimeout, commandType, buffered ? CommandFlags.Buffered : CommandFlags.None);
1753
            var results = MultiMapImpl<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(cnn, command, map, splitOn, null, null, true);
S
Sam Saffron 已提交
1754 1755 1756
            return buffered ? results.ToList() : results;
        }

1757
        static IEnumerable<TReturn> MultiMapImpl<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(this IDbConnection cnn, CommandDefinition command, Delegate map, string splitOn, IDataReader reader, Identity identity, bool finalize)
S
Sam Saffron 已提交
1758
        {
1759 1760
            object param = command.Parameters;
            identity = identity ?? new Identity(command.CommandText, command.CommandType, cnn, typeof(TFirst), param == null ? null : param.GetType(), new[] { typeof(TFirst), typeof(TSecond), typeof(TThird), typeof(TFourth), typeof(TFifth), typeof(TSixth), typeof(TSeventh) });
1761
            CacheInfo cinfo = GetCacheInfo(identity, param, command.AddToCache);
S
Sam Saffron 已提交
1762

1763 1764 1765
            IDbCommand ownedCommand = null;
            IDataReader ownedReader = null;

1766
            bool wasClosed = cnn != null && cnn.State == ConnectionState.Closed;
1767
            try
S
Sam Saffron 已提交
1768
            {
1769
                if (reader == null)
S
Sam Saffron 已提交
1770
                {
1771
                    ownedCommand = command.SetupCommand(cnn, cinfo.ParamReader);
1772
                    if (wasClosed) cnn.Open();
M
Marc Gravell 已提交
1773
                    ownedReader = ownedCommand.ExecuteReader(wasClosed ? CommandBehavior.CloseConnection | CommandBehavior.SequentialAccess : CommandBehavior.SequentialAccess);
1774 1775
                    reader = ownedReader;
                }
1776
                DeserializerState deserializer = default(DeserializerState);
M
mgravell 已提交
1777
                Func<IDataReader, object>[] otherDeserializers = null;
S
Sam Saffron 已提交
1778

1779 1780 1781
                int hash = GetColumnHash(reader);
                if ((deserializer = cinfo.Deserializer).Func == null || (otherDeserializers = cinfo.OtherDeserializers) == null || hash != deserializer.Hash)
                {
1782
                    var deserializers = GenerateDeserializers(new Type[] { typeof(TFirst), typeof(TSecond), typeof(TThird), typeof(TFourth), typeof(TFifth), typeof(TSixth), typeof(TSeventh) }, splitOn, reader);
1783
                    deserializer = cinfo.Deserializer = new DeserializerState(hash, deserializers[0]);
S
Sam Saffron 已提交
1784
                    otherDeserializers = cinfo.OtherDeserializers = deserializers.Skip(1).ToArray();
1785
                    if(command.AddToCache) SetQueryCache(identity, cinfo);
S
Sam Saffron 已提交
1786
                }
S
Sam Saffron 已提交
1787

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

S
Sam Saffron 已提交
1790 1791 1792
                if (mapIt != null)
                {
                    while (reader.Read())
1793
                    {
1794
                        yield return mapIt(reader);
1795
                    }
1796 1797 1798
                    if(finalize)
                    {
                        while (reader.NextResult()) { }
1799
                        command.OnCompleted();
1800
                    }                    
S
Sam Saffron 已提交
1801 1802 1803 1804 1805 1806 1807
                }
            }
            finally
            {
                try
                {
                    if (ownedReader != null)
1808
                    {
S
Sam Saffron 已提交
1809
                        ownedReader.Dispose();
1810
                    }
S
Sam Saffron 已提交
1811 1812 1813 1814
                }
                finally
                {
                    if (ownedCommand != null)
1815
                    {
S
Sam Saffron 已提交
1816
                        ownedCommand.Dispose();
1817
                    }
1818
                    if (wasClosed) cnn.Close();
1819
                }
S
Sam Saffron 已提交
1820 1821
            }
        }
1822

1823
        static IEnumerable<TReturn> MultiMapImpl<TReturn>(this IDbConnection cnn, CommandDefinition command, Type[] types, Func<object[], TReturn> map, string splitOn, IDataReader reader, Identity identity, bool finalize)
1824 1825 1826 1827 1828 1829 1830 1831
        {
            if (types.Length < 1)
            {
                throw new ArgumentException("you must provide at least one type to deserialize");
            }

            object param = command.Parameters;
            identity = identity ?? new Identity(command.CommandText, command.CommandType, cnn, types[0], param == null ? null : param.GetType(), types);
1832
            CacheInfo cinfo = GetCacheInfo(identity, param, command.AddToCache);
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866

            IDbCommand ownedCommand = null;
            IDataReader ownedReader = null;

            bool wasClosed = cnn != null && cnn.State == ConnectionState.Closed;
            try
            {
                if (reader == null)
                {
                    ownedCommand = command.SetupCommand(cnn, cinfo.ParamReader);
                    if (wasClosed) cnn.Open();
                    ownedReader = ownedCommand.ExecuteReader();
                    reader = ownedReader;
                }
                DeserializerState deserializer = default(DeserializerState);
                Func<IDataReader, object>[] otherDeserializers = null;

                int hash = GetColumnHash(reader);
                if ((deserializer = cinfo.Deserializer).Func == null || (otherDeserializers = cinfo.OtherDeserializers) == null || hash != deserializer.Hash)
                {
                    var deserializers = GenerateDeserializers(types, splitOn, reader);
                    deserializer = cinfo.Deserializer = new DeserializerState(hash, deserializers[0]);
                    otherDeserializers = cinfo.OtherDeserializers = deserializers.Skip(1).ToArray();
                    SetQueryCache(identity, cinfo);
                }

                Func<IDataReader, TReturn> mapIt = GenerateMapper(types.Length, deserializer.Func, otherDeserializers, map);

                if (mapIt != null)
                {
                    while (reader.Read())
                    {
                        yield return mapIt(reader);
                    }
1867 1868 1869
                    if (finalize)
                    {
                        while (reader.NextResult()) { }
1870
                        command.OnCompleted();
1871
                    }
S
Sam Saffron 已提交
1872 1873 1874 1875 1876 1877 1878
                }
            }
            finally
            {
                try
                {
                    if (ownedReader != null)
1879
                    {
S
Sam Saffron 已提交
1880
                        ownedReader.Dispose();
1881
                    }
S
Sam Saffron 已提交
1882 1883 1884 1885
                }
                finally
                {
                    if (ownedCommand != null)
1886
                    {
S
Sam Saffron 已提交
1887
                        ownedCommand.Dispose();
1888
                    }
1889
                    if (wasClosed) cnn.Close();
1890
                }
S
Sam Saffron 已提交
1891 1892
            }
        }
1893

1894
        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 已提交
1895
        {
1896
            switch (otherDeserializers.Length)
M
mgravell 已提交
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
            {
                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));
1907 1908 1909 1910
                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 已提交
1911
#endif
M
mgravell 已提交
1912 1913
                default:
                    throw new NotSupportedException();
S
Sam Saffron 已提交
1914 1915 1916
            }
        }

1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
        private static Func<IDataReader, TReturn> GenerateMapper<TReturn>(int length, Func<IDataReader, object> deserializer, Func<IDataReader, object>[] otherDeserializers, Func<object[], TReturn> map)
        {
            return r =>
            {
                var objects = new object[length];
                objects[0] = deserializer(r);

                for (var i = 1; i < length; ++i)
                {
                    objects[i] = otherDeserializers[i - 1](r);
                }

                return map(objects);
            };
        }

M
mgravell 已提交
1933
        private static Func<IDataReader, object>[] GenerateDeserializers(Type[] types, string splitOn, IDataReader reader)
S
Sam Saffron 已提交
1934
        {
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
            var deserializers = new List<Func<IDataReader, object>>();
            var splits = splitOn.Split(',').Select(s => s.Trim()).ToArray();
                bool isMultiSplit = splits.Length > 1;
            if (types.First() == typeof(Object))
            {
                // we go left to right for dynamic multi-mapping so that the madness of TestMultiMappingVariations
                // is supported
                bool first = true;
                int currentPos = 0;
                int splitIdx = 0;
                string currentSplit = splits[splitIdx];
                foreach (var type in types)
S
Sam Saffron 已提交
1947
                {
1948
                    if (type == typeof(DontMap))
1949
                    {
1950
                        break;
1951
                    }
S
Sam Saffron 已提交
1952

1953 1954 1955 1956 1957 1958 1959 1960
                    int splitPoint = GetNextSplitDynamic(currentPos, currentSplit, reader);
                    if (isMultiSplit && splitIdx < splits.Length - 1)
                    {
                        currentSplit = splits[++splitIdx];
                    }
                    deserializers.Add((GetDeserializer(type, reader, currentPos, splitPoint - currentPos, !first)));
                    currentPos = splitPoint;
                    first = false;
1961
                }
1962 1963 1964 1965 1966 1967 1968 1969 1970
            }
            else
            {
                // in this we go right to left through the data reader in order to cope with properties that are
                // named the same as a subsequent primary key that we split on
                int currentPos = reader.FieldCount;
                int splitIdx = splits.Length - 1;
                var currentSplit = splits[splitIdx];
                for (var typeIdx = types.Length - 1; typeIdx >= 0; --typeIdx)
1971
                {
1972 1973
                    var type = types[typeIdx];
                    if (type == typeof (DontMap))
1974
                    {
1975
                        continue;
1976
                    }
1977 1978 1979

                    int splitPoint = 0;
                    if (typeIdx > 0)
1980
                    {
1981 1982
                        splitPoint = GetNextSplit(currentPos, currentSplit, reader);
                        if (isMultiSplit && splitIdx > 0)
S
Sam Saffron 已提交
1983
                        {
1984
                            currentSplit = splits[--splitIdx];
S
Sam Saffron 已提交
1985
                        }
1986
                    }
1987 1988 1989

                    deserializers.Add((GetDeserializer(type, reader, splitPoint, currentPos - splitPoint, typeIdx > 0)));
                    currentPos = splitPoint;
S
Sam Saffron 已提交
1990
                }
S
Sam Saffron 已提交
1991

1992 1993 1994 1995 1996 1997 1998 1999 2000
                deserializers.Reverse();

            }
            return deserializers.ToArray();
        }

        private static int GetNextSplitDynamic(int startIdx, string splitOn, IDataReader reader)
        {
            if (startIdx == reader.FieldCount)
S
Sam Saffron 已提交
2001
            {
2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
                throw new ArgumentException(MultiMapSplitExceptionMessage);
            }

            if (splitOn == "*")
            {
                return ++startIdx;
            }

            for (var i = startIdx + 1; i < reader.FieldCount; ++i)
            {
                if (string.Equals(splitOn, reader.GetName(i), StringComparison.OrdinalIgnoreCase))
S
Sam Saffron 已提交
2013
                {
2014
                    return i;
S
Sam Saffron 已提交
2015
                }
S
Sam Saffron 已提交
2016
            }
S
Sam Saffron 已提交
2017

2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
            return reader.FieldCount;
        }

        private static int GetNextSplit(int startIdx, string splitOn, IDataReader reader)
        {
            if (splitOn == "*")
            {
                return --startIdx;
            }

            for (var i = startIdx - 1; i > 0; --i)
            {
                if (string.Equals(splitOn, reader.GetName(i), StringComparison.OrdinalIgnoreCase))
                {
                    return i;
                }
            }

            throw new ArgumentException(MultiMapSplitExceptionMessage);
2037 2038
        }

2039
        private static CacheInfo GetCacheInfo(Identity identity, object exampleParameters, bool addToCache)
S
Sam Saffron 已提交
2040 2041
        {
            CacheInfo info;
M
mgravell 已提交
2042
            if (!TryGetQueryCache(identity, out info))
S
Sam Saffron 已提交
2043 2044
            {
                info = new CacheInfo();
2045
                if (identity.parametersType != null)
S
Sam Saffron 已提交
2046
                {
2047
                    if (exampleParameters is IDynamicParameters)
S
Sam Saffron 已提交
2048
                    {
2049
                        info.ParamReader = (cmd, obj) => { ((IDynamicParameters)obj).AddParameters(cmd, identity); };
S
Sam Saffron 已提交
2050
                    }
2051
#if !CSHARP30
2052 2053
                    // special-case dictionary && `dynamic`
                    else if (exampleParameters is IEnumerable<KeyValuePair<string, object>> && exampleParameters is System.Dynamic.IDynamicMetaObjectProvider)
2054 2055 2056 2057 2058 2059 2060 2061
                    {
                        info.ParamReader = (cmd, obj) =>
                        {
                            IDynamicParameters mapped = new DynamicParameters(obj);
                            mapped.AddParameters(cmd, identity);
                        };
                    }
#endif
S
Sam Saffron 已提交
2062 2063
                    else
                    {
2064 2065
                        var literals = GetLiteralTokens(identity.sql);
                        info.ParamReader = CreateParamInfoGenerator(identity, false, true, literals);
S
Sam Saffron 已提交
2066
                    }
2067
                }
2068
                if(addToCache) SetQueryCache(identity, info);
2069
            }
S
Sam Saffron 已提交
2070
            return info;
2071 2072
        }

M
mgravell 已提交
2073
        private static Func<IDataReader, object> GetDeserializer(Type type, IDataReader reader, int startBound, int length, bool returnNullIfFirstMissing)
S
Sam Saffron 已提交
2074
        {
M
mgravell 已提交
2075
#if !CSHARP30
S
Sam Saffron 已提交
2076
            // dynamic is passed in as Object ... by c# design
M
mgravell 已提交
2077
            if (type == typeof(object)
2078
                || type == typeof(DapperRow))
S
Sam Saffron 已提交
2079
            {
2080
                return GetDapperRowDeserializer(reader, startBound, length, returnNullIfFirstMissing);
S
Sam Saffron 已提交
2081
            }
2082
#else
2083
            if (type.IsAssignableFrom(typeof(Dictionary<string, object>)))
2084 2085 2086
            {
                return GetDictionaryDeserializer(reader, startBound, length, returnNullIfFirstMissing);
            }
M
mgravell 已提交
2087
#endif
2088 2089 2090
            Type underlyingType = null;
            if (!(typeMap.ContainsKey(type) || type.IsEnum || type.FullName == LinqBinary ||
                (type.IsValueType && (underlyingType = Nullable.GetUnderlyingType(type)) != null && underlyingType.IsEnum)))
2091
            {
2092 2093 2094 2095 2096
                ITypeHandler handler;
                if (typeHandlers.TryGetValue(type, out handler))
                {
                    return GetHandlerDeserializer(handler, type, startBound);
                }
S
Sam Saffron 已提交
2097
                return GetTypeDeserializer(type, reader, startBound, length, returnNullIfFirstMissing);
2098
            }
2099
            return GetStructDeserializer(type, underlyingType ?? type, startBound);
2100
        }
2101 2102 2103 2104 2105
        static Func<IDataReader, object> GetHandlerDeserializer(ITypeHandler handler, Type type, int startBound)
        {
            return (IDataReader reader) =>
                handler.Parse(type, reader.GetValue(startBound));
        }
2106

M
mgravell 已提交
2107
#if !CSHARP30
M
Marc Gravell 已提交
2108
        private sealed partial class DapperTable
S
Sam Saffron 已提交
2109
        {
2110 2111
            string[] fieldNames;
            readonly Dictionary<string, int> fieldNameLookup;
S
Sam Saffron 已提交
2112

2113 2114 2115
            internal string[] FieldNames { get { return fieldNames; } }

            public DapperTable(string[] fieldNames)
S
Sam Saffron 已提交
2116
            {
2117 2118 2119 2120 2121 2122 2123 2124
                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];
2125
                    if (key != null) fieldNameLookup[key] = i;
2126
                }
S
Sam Saffron 已提交
2127 2128
            }

2129
            internal int IndexOfName(string name)
S
Sam Saffron 已提交
2130
            {
2131 2132 2133 2134 2135 2136 2137 2138 2139
                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
2140
                fieldNames[oldLen] = name;
2141 2142
                fieldNameLookup[name] = oldLen;
                return oldLen;
2143 2144
            }

2145 2146

            internal bool FieldExists(string key)
2147
            {
2148
                return key != null && fieldNameLookup.ContainsKey(key);
2149 2150
            }

2151 2152 2153 2154 2155 2156
            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();
2157
            static readonly MethodInfo setValueMethod = typeof(DapperRow).GetMethod("SetValue", new Type[] { typeof(string), typeof(object) });
2158 2159 2160 2161 2162 2163

            public DapperRowMetaObject(
                System.Linq.Expressions.Expression expression,
                System.Dynamic.BindingRestrictions restrictions
                )
                : base(expression, restrictions)
2164 2165 2166
            {
            }

2167 2168 2169 2170 2171 2172 2173 2174
            public DapperRowMetaObject(
                System.Linq.Expressions.Expression expression,
                System.Dynamic.BindingRestrictions restrictions,
                object value
                )
                : base(expression, restrictions, value)
            {
            }
2175

2176 2177 2178 2179
            System.Dynamic.DynamicMetaObject CallMethod(
                MethodInfo method,
                System.Linq.Expressions.Expression[] parameters
                )
2180
            {
2181 2182 2183 2184 2185 2186 2187 2188
                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;
2189 2190
            }

2191
            public override System.Dynamic.DynamicMetaObject BindGetMember(System.Dynamic.GetMemberBinder binder)
2192
            {
2193 2194 2195 2196 2197 2198 2199 2200
                var parameters = new System.Linq.Expressions.Expression[]
                                     {
                                         System.Linq.Expressions.Expression.Constant(binder.Name)
                                     };

                var callMethod = CallMethod(getValueMethod, parameters);

                return callMethod;
2201 2202
            }

2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
            // 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;
            }

2216
            public override System.Dynamic.DynamicMetaObject BindSetMember(System.Dynamic.SetMemberBinder binder, System.Dynamic.DynamicMetaObject value)
2217
            {
2218 2219 2220 2221 2222 2223 2224 2225 2226
                var parameters = new System.Linq.Expressions.Expression[]
                                     {
                                         System.Linq.Expressions.Expression.Constant(binder.Name),
                                         value.Expression,
                                     };

                var callMethod = CallMethod(setValueMethod, parameters);

                return callMethod;
2227
            }
2228
        }
2229

M
Marc Gravell 已提交
2230
        private sealed partial class DapperRow
2231 2232 2233 2234 2235 2236 2237
            : System.Dynamic.IDynamicMetaObjectProvider
            , IDictionary<string, object>
        {
            readonly DapperTable table;
            object[] values;

            public DapperRow(DapperTable table, object[] values)
2238
            {
2239 2240 2241 2242
                if (table == null) throw new ArgumentNullException("table");
                if (values == null) throw new ArgumentNullException("values");
                this.table = table;
                this.values = values;
2243
            }
2244 2245 2246 2247 2248 2249
            private sealed class DeadValue
            {
                public static readonly DeadValue Default = new DeadValue();
                private DeadValue() { }
            }
            int ICollection<KeyValuePair<string, object>>.Count
2250
            {
2251 2252 2253 2254 2255 2256 2257 2258 2259
                get
                {
                    int count = 0;
                    for (int i = 0; i < values.Length; i++)
                    {
                        if (!(values[i] is DeadValue)) count++;
                    }
                    return count;
                }
2260 2261
            }

2262
            public bool TryGetValue(string name, out object value)
2263
            {
2264 2265 2266 2267 2268 2269 2270 2271
                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;
2272 2273 2274 2275 2276
                if (value is DeadValue)
                { // pretend it isn't here
                    value = null;
                    return false;
                }
2277
                return true;
2278 2279
            }

2280 2281 2282 2283
            public override string ToString()
            {
                var sb = new StringBuilder("{DapperRow");
                foreach (var kv in this)
2284
                {
2285
                    var value = kv.Value;
2286
                    sb.Append(", ").Append(kv.Key);
2287 2288
                    if (value != null)
                    {
2289
                        sb.Append(" = '").Append(kv.Value).Append('\'');
2290 2291 2292 2293 2294
                    }
                    else
                    {
                        sb.Append(" = NULL");
                    }
2295
                }
2296

2297
                return sb.Append('}').ToString();
2298 2299
            }

2300 2301
            System.Dynamic.DynamicMetaObject System.Dynamic.IDynamicMetaObjectProvider.GetMetaObject(
                System.Linq.Expressions.Expression parameter)
2302 2303 2304 2305 2306 2307 2308 2309 2310 2311
            {
                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;
2312 2313 2314 2315
                    if (!(value is DeadValue))
                    {
                        yield return new KeyValuePair<string, object>(names[i], value);
                    }
2316 2317 2318 2319 2320 2321 2322
                }
            }

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

2324
#region Implementation of ICollection<KeyValuePair<string,object>>
2325 2326 2327

            void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item)
            {
2328 2329
                IDictionary<string, object> dic = this;
                dic.Add(item.Key, item.Value);
2330 2331 2332
            }

            void ICollection<KeyValuePair<string, object>>.Clear()
2333
            { // removes values for **this row**, but doesn't change the fundamental table
2334 2335
                for (int i = 0; i < values.Length; i++)
                    values[i] = DeadValue.Default;
2336 2337 2338 2339
            }

            bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item)
            {
2340 2341
                object value;
                return TryGetValue(item.Key, out value) && Equals(value, item.Value);
2342 2343 2344 2345
            }

            void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
            {
2346 2347 2348 2349
                foreach (var kv in this)
                {
                    array[arrayIndex++] = kv; // if they didn't leave enough space; not our fault
                }
2350 2351
            }

2352
            bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item)
2353
            {
2354 2355
                IDictionary<string, object> dic = this;
                return dic.Remove(item.Key);
2356 2357 2358 2359
            }

            bool ICollection<KeyValuePair<string, object>>.IsReadOnly
            {
2360
                get { return false; }
2361 2362
            }

2363
#endregion
2364

2365
#region Implementation of IDictionary<string,object>
2366 2367

            bool IDictionary<string, object>.ContainsKey(string key)
2368
            {
2369 2370 2371
                int index = table.IndexOfName(key);
                if (index < 0 || index >= values.Length || values[index] is DeadValue) return false;
                return true;
2372 2373
            }

2374 2375
            void IDictionary<string, object>.Add(string key, object value)
            {
2376
                SetValue(key, value, true);
2377
            }
2378

2379
            bool IDictionary<string, object>.Remove(string key)
2380
            {
2381
                int index = table.IndexOfName(key);
2382 2383 2384
                if (index < 0 || index >= values.Length || values[index] is DeadValue) return false;
                values[index] = DeadValue.Default;
                return true;
2385 2386
            }

2387 2388 2389
            object IDictionary<string, object>.this[string key]
            {
                get { object val; TryGetValue(key, out val); return val; }
2390
                set { SetValue(key, value, false); }
2391
            }
2392

2393
            public object SetValue(string key, object value)
2394 2395 2396 2397
            {
                return SetValue(key, value, false);
            }
            private object SetValue(string key, object value, bool isAdd)
2398 2399 2400 2401 2402 2403 2404
            {
                if (key == null) throw new ArgumentNullException("key");
                int index = table.IndexOfName(key);
                if (index < 0)
                {
                    index = table.AddField(key);
                }
2405 2406 2407 2408 2409 2410 2411 2412 2413
                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
2414 2415
                    // grow it to the full width of the table
                    Array.Resize(ref values, table.FieldCount);
2416 2417 2418 2419
                    for (int i = oldLength; i < values.Length; i++)
                    {
                        values[i] = DeadValue.Default;
                    }
2420
                }
2421
                return values[index] = value;
2422
            }
2423

2424 2425 2426 2427
            ICollection<string> IDictionary<string, object>.Keys
            {
                get { return this.Select(kv => kv.Key).ToArray(); }
            }
2428

2429
            ICollection<object> IDictionary<string, object>.Values
2430
            {
2431
                get { return this.Select(kv => kv.Value).ToArray(); }
2432 2433
            }

2434
#endregion
S
Sam Saffron 已提交
2435
        }
2436
#endif
2437
        private const string MultiMapSplitExceptionMessage = "When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id";
2438
#if !CSHARP30
2439 2440 2441 2442 2443 2444 2445
        internal static Func<IDataReader, object> GetDapperRowDeserializer(IDataRecord reader, int startBound, int length, bool returnNullIfFirstMissing)
        {
            var fieldCount = reader.FieldCount;
            if (length == -1)
            {
                length = fieldCount - startBound;
            }
2446

2447 2448
            if (fieldCount <= startBound)
            {
2449
                throw new ArgumentException(MultiMapSplitExceptionMessage, "splitOn");
2450 2451
            }

2452
            var effectiveFieldCount = Math.Min(fieldCount - startBound, length);
2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463

            DapperTable table = null;

            return
                r =>
                {
                    if (table == null)
                    {
                        string[] names = new string[effectiveFieldCount];
                        for (int i = 0; i < effectiveFieldCount; i++)
                        {
2464
                            names[i] = r.GetName(i + startBound);
2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482
                        }
                        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 已提交
2483 2484
                        for (int i = 0; i < values.Length; i++)
                            if (values[i] is DBNull) values[i] = null;
2485 2486 2487 2488 2489 2490
                    }
                    else
                    {
                        var begin = returnNullIfFirstMissing ? 1 : 0;
                        for (var iter = begin; iter < effectiveFieldCount; ++iter)
                        {
M
Marc Gravell 已提交
2491 2492
                            object obj = r.GetValue(iter + startBound);
                            values[iter] = obj is DBNull ? null : obj;
2493 2494 2495 2496 2497 2498 2499
                        }
                    }
                    return new DapperRow(table, values);
                };
        }
#else
        internal static Func<IDataReader, object> GetDictionaryDeserializer(IDataRecord reader, int startBound, int length, bool returnNullIfFirstMissing)
S
Sam Saffron 已提交
2500
        {
2501
            var fieldCount = reader.FieldCount;
2502 2503
            if (length == -1)
            {
2504 2505 2506 2507 2508
                length = fieldCount - startBound;
            }

            if (fieldCount <= startBound)
            {
2509
                throw new ArgumentException(MultiMapSplitExceptionMessage, "splitOn");
2510 2511
            }

2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522
            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 已提交
2523
                             return null;
2524 2525
                         }
                     }
2526
                     return row;
2527
                 };
S
Sam Saffron 已提交
2528
        }
2529
#endif
S
Sam Saffron 已提交
2530 2531 2532 2533 2534
        /// <summary>
        /// Internal use only
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
M
mgravell 已提交
2535 2536 2537 2538 2539 2540 2541
        [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");
2542
            return s[0];
M
mgravell 已提交
2543
        }
S
Sam Saffron 已提交
2544 2545 2546 2547

        /// <summary>
        /// Internal use only
        /// </summary>
M
mgravell 已提交
2548 2549 2550 2551 2552 2553 2554
        [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");
2555
            return s[0];
M
mgravell 已提交
2556
        }
2557

2558

2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579
        /// <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 已提交
2580 2581 2582
        /// <summary>
        /// Internal use only
        /// </summary>
2583
        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
2584
        [Obsolete("This method is for internal usage only", false)]
2585 2586 2587 2588 2589
        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

2590
            if (FeatureSupport.Get(command.Connection).Arrays)
2591
            {
2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603
                var arrayParm = command.CreateParameter();
                arrayParm.Value = value ?? DBNull.Value;
                arrayParm.ParameterName = namePrefix;
                command.Parameters.Add(arrayParm);
            }
            else
            {
                var list = value as IEnumerable;
                var count = 0;
                bool isString = value is IEnumerable<string>;
                bool isDbString = value is IEnumerable<DbString>;
                foreach (var item in list)
2604
                {
2605 2606 2607 2608 2609
                    count++;
                    var listParam = command.CreateParameter();
                    listParam.ParameterName = namePrefix + count;
                    listParam.Value = item ?? DBNull.Value;
                    if (isString)
2610
                    {
2611 2612
                        listParam.Size = DbString.DefaultLength;
                        if (item != null && ((string)item).Length > DbString.DefaultLength)
2613
                        {
2614
                            listParam.Size = -1;
2615
                        }
2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634
                    }
                    if (isDbString && item as DbString != null)
                    {
                        var str = item as DbString;
                        str.AddParameter(command, listParam.ParameterName);
                    }
                    else
                    {
                        command.Parameters.Add(listParam);
                    }
                }

                var regexIncludingUnknown = @"([?@:]" + Regex.Escape(namePrefix) + @")(\s+(?i)unknown(?-i))?";
                if (count == 0)
                {
                    command.CommandText = Regex.Replace(command.CommandText, regexIncludingUnknown, match =>
                    {
                        var variableName = match.Groups[1].Value;
                        if (match.Groups[2].Success)
2635
                        {
2636 2637
                            // looks like an optimize hint; leave it alone!
                            return match.Value;
2638 2639 2640
                        }
                        else
                        {
2641
                            return "(SELECT " + variableName + " WHERE 1 = 0)";
2642
                        }
2643 2644 2645 2646 2647 2648 2649 2650 2651
                    });                        
                    var dummyParam = command.CreateParameter();
                    dummyParam.ParameterName = namePrefix;
                    dummyParam.Value = DBNull.Value;
                    command.Parameters.Add(dummyParam);
                }
                else
                {
                    command.CommandText = Regex.Replace(command.CommandText, regexIncludingUnknown, match =>
2652
                    {
2653 2654
                        var variableName = match.Groups[1].Value;
                        if (match.Groups[2].Success)
2655
                        {
2656 2657 2658 2659 2660
                            // looks like an optimize hint; expand it
                            var suffix = match.Groups[2].Value;
                                
                            var sb = new StringBuilder(variableName).Append(1).Append(suffix);
                            for (int i = 2; i <= count; i++)
2661
                            {
2662
                                sb.Append(',').Append(variableName).Append(i).Append(suffix);
2663
                            }
2664 2665 2666
                            return sb.ToString();
                        }
                        else
2667
                        {
2668 2669
                            var sb = new StringBuilder("(").Append(variableName).Append(1);
                            for (int i = 2; i <= count; i++)
2670
                            {
2671
                                sb.Append(',').Append(variableName).Append(i);
2672
                            }
2673 2674 2675
                            return sb.Append(')').ToString();
                        }
                    });
2676
                }
2677
            }
S
Sam Saffron 已提交
2678

2679
        }
S
Sam Saffron 已提交
2680

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

2686 2687

        // look for ? / @ / : *by itself*
2688
        static readonly Regex smellsLikeOleDb = new Regex(@"(?<![a-zA-Z0-9@_])[?@:](?![a-zA-Z0-9@_])", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Compiled),
2689
            literalTokens = new Regex(@"\{=([a-zA-Z0-9_]+)\}", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Compiled);
2690
        
2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722
        /// <summary>
        /// Represents a placeholder for a value that should be replaced as a literal value in the resulting sql
        /// </summary>
        internal struct LiteralToken
        {
            private readonly string token, member;
            /// <summary>
            /// The text in the original command that should be replaced
            /// </summary>
            public string Token { get { return token; } }

            /// <summary>
            /// The name of the member referred to by the token
            /// </summary>
            public string Member { get { return member; } }
            internal LiteralToken(string token, string member)
            {
                this.token = token;
                this.member = member;
            }

            internal static readonly IList<LiteralToken> None = new LiteralToken[0];
        }

        /// <summary>
        /// Replace all literal tokens with their text form
        /// </summary>
        public static void ReplaceLiterals(this IParameterLookup parameters, IDbCommand command)
        {
            var tokens = GetLiteralTokens(command.CommandText);
            if (tokens.Count != 0) ReplaceLiterals(parameters, command, tokens);
        }
2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765

        internal static readonly MethodInfo format = typeof(SqlMapper).GetMethod("Format", BindingFlags.Public | BindingFlags.Static);
        /// <summary>
        /// Convert numeric values to their string form for SQL literal purposes
        /// </summary>
        [Obsolete("This is intended for internal usage only")]
        public static string Format(object value)
        {
            if (value == null)
            {
                return "null";
            }
            else
            {
                switch (Type.GetTypeCode(value.GetType()))
                {
                    case TypeCode.DBNull:
                        return "null";
                    case TypeCode.Boolean:
                        return ((bool)value) ? "1" : "0";
                    case TypeCode.Byte:
                        return ((byte)value).ToString(CultureInfo.InvariantCulture);
                    case TypeCode.SByte:
                        return ((sbyte)value).ToString(CultureInfo.InvariantCulture);
                    case TypeCode.UInt16:
                        return ((ushort)value).ToString(CultureInfo.InvariantCulture);
                    case TypeCode.Int16:
                        return ((short)value).ToString(CultureInfo.InvariantCulture);
                    case TypeCode.UInt32:
                        return ((uint)value).ToString(CultureInfo.InvariantCulture);
                    case TypeCode.Int32:
                        return ((int)value).ToString(CultureInfo.InvariantCulture);
                    case TypeCode.UInt64:
                        return ((ulong)value).ToString(CultureInfo.InvariantCulture);
                    case TypeCode.Int64:
                        return ((long)value).ToString(CultureInfo.InvariantCulture);
                    case TypeCode.Single:
                        return ((float)value).ToString(CultureInfo.InvariantCulture);
                    case TypeCode.Double:
                        return ((double)value).ToString(CultureInfo.InvariantCulture);
                    case TypeCode.Decimal:
                        return ((decimal)value).ToString(CultureInfo.InvariantCulture);
                    default:
2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783
                        if(value is IEnumerable && !(value is string))
                        {
                            var sb = new StringBuilder();
                            bool first = true;
                            foreach (object subval in (IEnumerable)value)
                            {
                                sb.Append(first ? '(' : ',').Append(Format(subval));
                                first = false;
                            }
                            if(first)
                            {
                                return "(select null where 1=0)";
                            }
                            else
                            {
                                return sb.Append(')').ToString();
                            }
                        }
2784 2785 2786 2787
                        throw new NotSupportedException(value.GetType().Name);
                }
            }
        }
2788 2789


2790 2791 2792 2793 2794 2795
        internal static void ReplaceLiterals(IParameterLookup parameters, IDbCommand command, IList<LiteralToken> tokens)
        {
            var sql = command.CommandText;
            foreach (var token in tokens)
            {
                object value = parameters[token.Member];
2796 2797 2798
#pragma warning disable 0618
                string text = Format(value);
#pragma warning restore 0618
2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822
                sql = sql.Replace(token.Token, text);
            }
            command.CommandText = sql;
        }

        internal static IList<LiteralToken> GetLiteralTokens(string sql)
        {
            if (string.IsNullOrEmpty(sql)) return LiteralToken.None;
            if (!literalTokens.IsMatch(sql)) return LiteralToken.None;

            var matches = literalTokens.Matches(sql);
            var found = new HashSet<string>(StringComparer.InvariantCulture);
            List<LiteralToken> list = new List<LiteralToken>(matches.Count);
            foreach(Match match in matches)
            {
                string token = match.Value;
                if(found.Add(match.Value))
                {
                    list.Add(new LiteralToken(token, match.Groups[1].Value));
                }
            }
            return list.Count == 0 ? LiteralToken.None : list;
        }

S
Sam Saffron 已提交
2823 2824 2825
        /// <summary>
        /// Internal use only
        /// </summary>
2826
        public static Action<IDbCommand, object> CreateParamInfoGenerator(Identity identity, bool checkForDuplicates, bool removeUnused)
2827 2828 2829 2830 2831
        {
            return CreateParamInfoGenerator(identity, checkForDuplicates, removeUnused, GetLiteralTokens(identity.sql));
        }

        internal static Action<IDbCommand, object> CreateParamInfoGenerator(Identity identity, bool checkForDuplicates, bool removeUnused, IList<LiteralToken> literals)
S
Sam Saffron 已提交
2832
        {
2833
            Type type = identity.parametersType;
2834 2835 2836 2837 2838 2839
            
            bool filterParams = false;
            if (removeUnused && identity.commandType.GetValueOrDefault(CommandType.Text) == CommandType.Text)
            {
                filterParams = !smellsLikeOleDb.IsMatch(identity.sql);
            }
2840
            var dm = new DynamicMethod(string.Format("ParamInfo{0}", Guid.NewGuid()), null, new[] { typeof(IDbCommand), typeof(object) }, type, true);
S
Sam Saffron 已提交
2841 2842 2843 2844

            var il = dm.GetILGenerator();

            il.DeclareLocal(type); // 0
2845 2846
            bool haveInt32Arg1 = false;
            il.Emit(OpCodes.Ldarg_1); // stack is now [untyped-param]
S
Sam Saffron 已提交
2847 2848 2849
            il.Emit(OpCodes.Unbox_Any, type); // stack is now [typed-param]
            il.Emit(OpCodes.Stloc_0);// stack is now empty

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

2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904
            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);
2905 2906 2907 2908
            if (filterParams)
            {
                props = FilterParameters(props, identity.sql);
            }
2909

2910
            foreach (var prop in props)
S
Sam Saffron 已提交
2911
            {
2912
                if (typeof(ICustomQueryParameter).IsAssignableFrom(prop.PropertyType))
M
mgravell 已提交
2913 2914
                {
                    il.Emit(OpCodes.Ldloc_0); // stack is now [parameters] [typed-param]
2915 2916 2917
                    il.Emit(OpCodes.Callvirt, prop.GetGetMethod()); // stack is [parameters] [custom]
                    il.Emit(OpCodes.Ldarg_0); // stack is now [parameters] [custom] [command]
                    il.Emit(OpCodes.Ldstr, prop.Name); // stack is now [parameters] [custom] [command] [name]
2918
                    il.EmitCall(OpCodes.Callvirt, prop.PropertyType.GetMethod("AddParameter"), null); // stack is now [parameters]
M
mgravell 已提交
2919 2920
                    continue;
                }
2921 2922
                ITypeHandler handler;
                DbType dbType = LookupDbType(prop.PropertyType, prop.Name, out handler);
2923
                if (dbType == DynamicParameters.EnumerableMultiParameter)
2924 2925 2926
                {
                    // this actually represents special handling for list types;
                    il.Emit(OpCodes.Ldarg_0); // stack is now [parameters] [command]
2927
                    il.Emit(OpCodes.Ldstr, prop.Name); // stack is now [parameters] [command] [name]
2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940
                    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]

2941 2942 2943 2944 2945 2946 2947 2948 2949 2950
                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]
2951

2952 2953 2954 2955
                    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]
                }
2956
                if (dbType != DbType.Time && handler == null) // 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 已提交
2957
                {
2958 2959
                    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 已提交
2960

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

2964 2965 2966
                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]
2967

2968 2969 2970
                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]
2971
                bool checkForNull = true;
S
Sam Saffron 已提交
2972 2973
                if (prop.PropertyType.IsValueType)
                {
2974
                    il.Emit(OpCodes.Box, prop.PropertyType); // stack is [parameters] [[parameters]] [parameter] [parameter] [boxed-value]
2975 2976 2977 2978
                    if (Nullable.GetUnderlyingType(prop.PropertyType) == null)
                    {   // struct but not Nullable<T>; boxed value cannot be null
                        checkForNull = false;
                    }
S
Sam Saffron 已提交
2979
                }
2980 2981
                if (checkForNull)
                {
2982
                    if ((dbType == DbType.String || dbType == DbType.AnsiString) && !haveInt32Arg1)
2983 2984 2985 2986 2987 2988 2989
                    {
                        il.DeclareLocal(typeof(int));
                        haveInt32Arg1 = true;
                    }
                    // relative stack: [boxed value]
                    il.Emit(OpCodes.Dup);// relative stack: [boxed value] [boxed value]
                    Label notNull = il.DefineLabel();
2990
                    Label? allDone = (dbType == DbType.String || dbType == DbType.AnsiString) ? il.DefineLabel() : (Label?)null;
2991 2992 2993 2994
                    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]
2995
                    if (dbType == DbType.String || dbType == DbType.AnsiString)
2996 2997 2998 2999 3000 3001 3002 3003 3004 3005
                    {
                        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]
3006
                        EmitInt32(il, DbString.DefaultLength); // [string] [length] [4000]
3007 3008 3009
                        il.Emit(OpCodes.Cgt); // [string] [0 or 1]
                        Label isLong = il.DefineLabel(), lenDone = il.DefineLabel();
                        il.Emit(OpCodes.Brtrue_S, isLong);
3010
                        EmitInt32(il, DbString.DefaultLength); // [string] [4000]
3011 3012 3013 3014 3015 3016
                        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 已提交
3017
                    if (prop.PropertyType.FullName == LinqBinary)
M
mgravell 已提交
3018
                    {
M
mgravell 已提交
3019
                        il.EmitCall(OpCodes.Callvirt, prop.PropertyType.GetMethod("ToArray", BindingFlags.Public | BindingFlags.Instance), null);
M
mgravell 已提交
3020
                    }
3021 3022 3023
                    if (allDone != null) il.MarkLabel(allDone.Value);
                    // relative stack [boxed value or DBNull]
                }
3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034

                if (handler != null)
                {
#pragma warning disable 618
                    il.Emit(OpCodes.Call, typeof(TypeHandlerCache<>).MakeGenericType(prop.PropertyType).GetMethod("SetValue")); // stack is now [parameters] [[parameters]] [parameter]
#pragma warning restore 618
                }
                else
                {
                    il.EmitCall(OpCodes.Callvirt, typeof(IDataParameter).GetProperty("Value").GetSetMethod(), null);// stack is now [parameters] [[parameters]] [parameter]
                }
S
Sam Saffron 已提交
3035

3036 3037 3038 3039
                if (prop.PropertyType == typeof(string))
                {
                    var endOfSize = il.DefineLabel();
                    // don't set if 0
3040 3041
                    il.Emit(OpCodes.Ldloc_1); // [parameters] [[parameters]] [parameter] [size]
                    il.Emit(OpCodes.Brfalse_S, endOfSize); // [parameters] [[parameters]] [parameter]
3042

3043 3044 3045
                    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 已提交
3046

3047 3048
                    il.MarkLabel(endOfSize);
                }
3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060
                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
                }
3061
            }
3062

3063
            // stack is currently [parameters]
3064
            il.Emit(OpCodes.Pop); // stack is now empty
3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099

            if(literals.Count != 0 && propsArr != null)
            {
                il.Emit(OpCodes.Ldarg_0); // command
                il.Emit(OpCodes.Ldarg_0); // command, command
                var cmdText = typeof(IDbCommand).GetProperty("CommandText");
                il.EmitCall(OpCodes.Callvirt, cmdText.GetGetMethod(), null); // command, sql
                Dictionary<Type, LocalBuilder> locals = null;
                LocalBuilder local = null;
                foreach (var literal in literals)
                {
                    // find the best member, preferring case-sensitive
                    PropertyInfo exact = null, fallback = null;
                    string huntName = literal.Member;
                    for(int i = 0; i < propsArr.Length;i++)
                    {
                        string thisName = propsArr[i].Name;
                        if(string.Equals(thisName, huntName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            fallback = propsArr[i];
                            if(string.Equals(thisName, huntName, StringComparison.InvariantCulture))
                            {
                                exact = fallback;
                                break;
                            }
                        }
                    }
                    var prop = exact ?? fallback;

                    if(prop != null)
                    {
                        il.Emit(OpCodes.Ldstr, literal.Token);
                        il.Emit(OpCodes.Ldloc_0); // command, sql, typed parameter
                        il.EmitCall(OpCodes.Callvirt, prop.GetGetMethod(), null); // command, sql, typed value
                        Type propType = prop.PropertyType;
3100 3101
                        var typeCode = Type.GetTypeCode(propType);
                        switch (typeCode)
3102
                        {
3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114
                            case TypeCode.Boolean:
                            case TypeCode.Byte:
                            case TypeCode.SByte:
                            case TypeCode.UInt16:
                            case TypeCode.Int16:
                            case TypeCode.UInt32:
                            case TypeCode.Int32:
                            case TypeCode.UInt64:
                            case TypeCode.Int64:
                            case TypeCode.Single:
                            case TypeCode.Double:
                            case TypeCode.Decimal:
3115 3116
                                // neeed to stloc, ldloca, call
                                // re-use existing locals (both the last known, and via a dictionary)
3117
                                var convert = GetToString(typeCode);
3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138
                                if (local == null || local.LocalType != propType)
                                {
                                    if (locals == null)
                                    {
                                        locals = new Dictionary<Type, LocalBuilder>();
                                        local = null;
                                    }
                                    else
                                    {
                                        if (!locals.TryGetValue(propType, out local)) local = null;
                                    }
                                    if (local == null)
                                    {
                                        local = il.DeclareLocal(propType);
                                        locals.Add(propType, local);
                                    }
                                }
                                il.Emit(OpCodes.Stloc, local); // command, sql
                                il.Emit(OpCodes.Ldloca, local); // command, sql, ref-to-value
                                il.EmitCall(OpCodes.Call, InvariantCulture, null); // command, sql, ref-to-value, culture
                                il.EmitCall(OpCodes.Call, convert, null); // command, sql, string value
3139 3140 3141 3142 3143 3144
                                break;
                            default:
                                if (propType.IsValueType) il.Emit(OpCodes.Box, propType); // command, sql, object value
                                il.EmitCall(OpCodes.Call, format, null); // command, sql, string value
                                break;

3145 3146 3147 3148 3149 3150 3151
                        }
                        il.EmitCall(OpCodes.Callvirt, StringReplace, null);
                    }
                }
                il.EmitCall(OpCodes.Callvirt, cmdText.GetSetMethod(), null); // empty
            }

3152 3153
            il.Emit(OpCodes.Ret);
            return (Action<IDbCommand, object>)dm.CreateDelegate(typeof(Action<IDbCommand, object>));
S
Sam Saffron 已提交
3154
        }
3155
        static readonly Dictionary<TypeCode, MethodInfo> toStrings = new[]
3156
        {
3157 3158 3159 3160 3161 3162 3163
            typeof(bool), typeof(sbyte), typeof(byte), typeof(ushort), typeof(short),
            typeof(uint), typeof(int), typeof(ulong), typeof(long), typeof(float), typeof(double), typeof(decimal)
        }.ToDictionary(x => Type.GetTypeCode(x), x => x.GetMethod("ToString", BindingFlags.Public | BindingFlags.Instance, null, new[] { typeof(IFormatProvider) }, null));
        static MethodInfo GetToString(TypeCode typeCode)
        {
            MethodInfo method;
            return toStrings.TryGetValue(typeCode, out method) ? method : null;
3164 3165 3166
        }
        static readonly MethodInfo StringReplace = typeof(string).GetMethod("Replace", BindingFlags.Instance | BindingFlags.Public, null, new Type[] { typeof(string), typeof(string) }, null),
            InvariantCulture = typeof(CultureInfo).GetProperty("InvariantCulture", BindingFlags.Public | BindingFlags.Static).GetGetMethod();
S
Sam Saffron 已提交
3167

3168
        private static int ExecuteCommand(IDbConnection cnn, ref CommandDefinition command, Action<IDbCommand, object> paramReader)
S
Sam Saffron 已提交
3169
        {
3170 3171 3172
            IDbCommand cmd = null;
            bool wasClosed = cnn.State == ConnectionState.Closed;
            try
S
Sam Saffron 已提交
3173
            {
3174
                cmd = command.SetupCommand(cnn, paramReader);
3175
                if (wasClosed) cnn.Open();
3176
                int result = cmd.ExecuteNonQuery();
3177
                command.OnCompleted();
3178
                return result;
S
Sam Saffron 已提交
3179
            }
3180 3181 3182 3183 3184
            finally
            {
                if (wasClosed) cnn.Close();
                if (cmd != null) cmd.Dispose();
            }
S
Sam Saffron 已提交
3185 3186
        }

3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204
        private static T ExecuteScalarImpl<T>(IDbConnection cnn, ref CommandDefinition command)
        {
            Action<IDbCommand, object> paramReader = null;
            object param = command.Parameters;
            if (param != null)
            {
                var identity = new Identity(command.CommandText, command.CommandType, cnn, null, param.GetType(), null);
                paramReader = GetCacheInfo(identity, command.Parameters, command.AddToCache).ParamReader;
            }

            IDbCommand cmd = null;
            bool wasClosed = cnn.State == ConnectionState.Closed;
            object result;
            try
            {
                cmd = command.SetupCommand(cnn, paramReader);
                if (wasClosed) cnn.Open();
                result =cmd.ExecuteScalar();
3205
                command.OnCompleted();
3206 3207 3208 3209 3210 3211 3212 3213 3214
            }
            finally
            {
                if (wasClosed) cnn.Close();
                if (cmd != null) cmd.Dispose();
            }
            return Parse<T>(result);
        }

M
Marc Gravell 已提交
3215
        private static IDataReader ExecuteReaderImpl(IDbConnection cnn, ref CommandDefinition command, CommandBehavior commandBehavior)
J
JJoe2 已提交
3216
        {
3217 3218
            Action<IDbCommand, object> paramReader = GetParameterReader(cnn, ref command);

J
JJoe2 已提交
3219 3220 3221 3222
            IDbCommand cmd = null;
            bool wasClosed = cnn.State == ConnectionState.Closed;
            try
            {
3223
                cmd = command.SetupCommand(cnn, paramReader);
J
JJoe2 已提交
3224
                if (wasClosed) cnn.Open();
M
Marc Gravell 已提交
3225 3226 3227
                if (wasClosed) commandBehavior |= CommandBehavior.CloseConnection;
                var reader = cmd.ExecuteReader(commandBehavior);
                wasClosed = false; // don't dispose before giving it to them!
3228 3229

                // note: command.FireOutputCallbacks(); would be useless here; parameters come at the **end** of the TDS stream
J
JJoe2 已提交
3230 3231 3232 3233 3234 3235 3236 3237 3238
                return reader;
            }
            finally
            {
                if (wasClosed) cnn.Close();
                if (cmd != null) cmd.Dispose();
            }
        }

3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253
        private static Action<IDbCommand, object> GetParameterReader(IDbConnection cnn, ref CommandDefinition command)
        {
            object param = command.Parameters;
            IEnumerable multiExec = (object)param as IEnumerable;
            Identity identity;
            CacheInfo info = null;
            if (multiExec != null && !(multiExec is string))
            {
                throw new NotSupportedException("MultiExec is not supported by ExecuteReader");
            }

            // nice and simple
            if (param != null)
            {
                identity = new Identity(command.CommandText, command.CommandType, cnn, null, param.GetType(), null);
3254
                info = GetCacheInfo(identity, param, command.AddToCache);
3255 3256 3257 3258 3259
            }
            var paramReader = info == null ? null : info.ParamReader;
            return paramReader;
        }

3260
        private static Func<IDataReader, object> GetStructDeserializer(Type type, Type effectiveType, int index)
S
Sam Saffron 已提交
3261
        {
M
mgravell 已提交
3262 3263
            // 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 已提交
3264
            if (type == typeof(char))
M
mgravell 已提交
3265
            { // this *does* need special handling, though
M
mgravell 已提交
3266
                return r => SqlMapper.ReadChar(r.GetValue(index));
M
mgravell 已提交
3267
            }
M
mgravell 已提交
3268
            if (type == typeof(char?))
M
mgravell 已提交
3269
            {
M
mgravell 已提交
3270
                return r => SqlMapper.ReadNullableChar(r.GetValue(index));
M
mgravell 已提交
3271
            }
M
mgravell 已提交
3272
            if (type.FullName == LinqBinary)
M
mgravell 已提交
3273
            {
M
mgravell 已提交
3274
                return r => Activator.CreateInstance(type, r.GetValue(index));
M
mgravell 已提交
3275
            }
M
mgravell 已提交
3276
#pragma warning restore 618
3277 3278 3279 3280 3281 3282

            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);
3283 3284 3285 3286
                    if(val is float || val is double || val is decimal)
                    {
                        val = Convert.ChangeType(val, Enum.GetUnderlyingType(effectiveType), CultureInfo.InvariantCulture);
                    }
3287 3288 3289
                    return val is DBNull ? null : Enum.ToObject(effectiveType, val);
                };
            }
3290 3291 3292 3293 3294 3295 3296 3297 3298
            ITypeHandler handler;
            if(typeHandlers.TryGetValue(type, out handler))
            {
                return r =>
                {
                    var val = r.GetValue(index);
                    return val is DBNull ? null : handler.Parse(type, val);
                };
            }
3299
            return r =>
S
Sam Saffron 已提交
3300
            {
3301
                var val = r.GetValue(index);
M
mgravell 已提交
3302
                return val is DBNull ? null : val;
S
Sam Saffron 已提交
3303
            };
S
Sam Saffron 已提交
3304
        }
3305

3306 3307 3308 3309 3310
        private static T Parse<T>(object value)
        {
            if (value == null || value is DBNull) return default(T);
            if (value is T) return (T)value;
            var type = typeof(T);
3311
            type = Nullable.GetUnderlyingType(type) ?? type;
3312 3313
            if (type.IsEnum)
            {
3314 3315 3316 3317
                if (value is float || value is double || value is decimal)
                {
                    value = Convert.ChangeType(value, Enum.GetUnderlyingType(type), CultureInfo.InvariantCulture);
                }
3318 3319 3320 3321 3322 3323 3324 3325 3326 3327
                return (T)Enum.ToObject(type, value);
            }
            ITypeHandler handler;
            if (typeHandlers.TryGetValue(type, out handler))
            {
                return (T)handler.Parse(type, value);
            }
            return (T)Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
        }

M
mgravell 已提交
3328 3329 3330 3331 3332
        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 已提交
3333

3334
        /// <summary>
3335
        /// Gets type-map for the given type
3336
        /// </summary>
3337
        /// <returns>Type map implementation, DefaultTypeMap instance if no override present</returns>
3338
        public static ITypeMap GetTypeMap(Type type)
3339
        {
3340 3341
            if (type == null) throw new ArgumentNullException("type");
            var map = (ITypeMap)_typeMaps[type];
3342
            if (map == null)
3343
            {
3344
                lock (_typeMaps)
3345 3346 3347
                {   // 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];
3348
                    if (map == null)
3349 3350 3351 3352 3353
                    {
                        map = new DefaultTypeMap(type);
                        _typeMaps[type] = map;
                    }
                }
3354
            }
3355
            return map;
3356 3357
        }

3358 3359
        // use Hashtable to get free lockless reading
        private static readonly Hashtable _typeMaps = new Hashtable();
3360 3361 3362 3363 3364 3365 3366

        /// <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)
3367
        {
3368 3369 3370 3371
            if (type == null)
                throw new ArgumentNullException("type");

            if (map == null || map is DefaultTypeMap)
3372
            {
3373
                lock (_typeMaps)
3374
                {
3375
                    _typeMaps.Remove(type);
3376 3377
                }
            }
3378
            else
3379
            {
3380
                lock (_typeMaps)
3381
                {
3382
                    _typeMaps[type] = map;
3383 3384
                }
            }
3385 3386

            PurgeQueryCacheByType(type);
3387 3388
        }

S
Sam Saffron 已提交
3389 3390 3391 3392 3393 3394 3395 3396 3397
        /// <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 已提交
3398
        public static Func<IDataReader, object> GetTypeDeserializer(
M
mgravell 已提交
3399
#if CSHARP30
3400
Type type, IDataReader reader, int startBound, int length, bool returnNullIfFirstMissing
M
mgravell 已提交
3401
#else
3402
Type type, IDataReader reader, int startBound = 0, int length = -1, bool returnNullIfFirstMissing = false
3403 3404
#endif
)
S
Sam Saffron 已提交
3405
        {
3406

3407
            var dm = new DynamicMethod(string.Format("Deserialize{0}", Guid.NewGuid()), typeof(object), new[] { typeof(IDataReader) }, true);
S
Sam Saffron 已提交
3408
            var il = dm.GetILGenerator();
M
mgravell 已提交
3409
            il.DeclareLocal(typeof(int));
3410
            il.DeclareLocal(type);
M
mgravell 已提交
3411 3412
            il.Emit(OpCodes.Ldc_I4_0);
            il.Emit(OpCodes.Stloc_0);
3413

S
Sam Saffron 已提交
3414 3415 3416 3417 3418
            if (length == -1)
            {
                length = reader.FieldCount - startBound;
            }

3419 3420
            if (reader.FieldCount <= startBound)
            {
3421
                throw new ArgumentException(MultiMapSplitExceptionMessage, "splitOn");
3422 3423
            }

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

3426
            ITypeMap typeMap = GetTypeMap(type);
S
Sam Saffron 已提交
3427

S
Sam Saffron 已提交
3428
            int index = startBound;
S
Sam Saffron 已提交
3429

3430
            ConstructorInfo specializedConstructor = null;
3431

M
Marc Gravell 已提交
3432
            bool supportInitialize = false;
S
Sam Saffron 已提交
3433 3434
            if (type.IsValueType)
            {
3435
                il.Emit(OpCodes.Ldloca_S, (byte)1);
S
Sam Saffron 已提交
3436 3437 3438 3439
                il.Emit(OpCodes.Initobj, type);
            }
            else
            {
V
vosen 已提交
3440
                var types = new Type[length];
3441
                for (int i = startBound; i < startBound + length; i++)
3442
                {
3443 3444
                    types[i - startBound] = reader.GetFieldType(i);
                }
3445

3446 3447
                var ctor = typeMap.FindConstructor(names, types);
                if (ctor == null)
3448
                {
3449 3450
                    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));
3451
                }
3452

3453 3454 3455 3456
                if (ctor.GetParameters().Length == 0)
                {
                    il.Emit(OpCodes.Newobj, ctor);
                    il.Emit(OpCodes.Stloc_1);
M
Marc Gravell 已提交
3457 3458 3459 3460 3461 3462
                    supportInitialize = typeof(ISupportInitialize).IsAssignableFrom(type);
                    if(supportInitialize)
                    {
                        il.Emit(OpCodes.Ldloc_1);
                        il.EmitCall(OpCodes.Callvirt, typeof(ISupportInitialize).GetMethod("BeginInit"), null);
                    }
3463
                }
3464 3465
                else
                    specializedConstructor = ctor;
3466
            }
3467

3468
            il.BeginExceptionBlock();
3469
            if (type.IsValueType)
3470 3471
            {
                il.Emit(OpCodes.Ldloca_S, (byte)1);// [target]
3472
            }
3473
            else if (specializedConstructor == null)
3474 3475
            {
                il.Emit(OpCodes.Ldloc_1);// [target]
S
Sam Saffron 已提交
3476 3477
            }

3478
            var members = (specializedConstructor != null
3479 3480
                ? names.Select(n => typeMap.GetConstructorParameter(specializedConstructor, n))
                : names.Select(n => typeMap.GetMember(n))).ToList();
V
vosen 已提交
3481

S
Sam Saffron 已提交
3482 3483
            // stack is now [target]

3484
            bool first = true;
3485
            var allDone = il.DefineLabel();
3486
            int enumDeclareLocal = -1, valueCopyLocal = il.DeclareLocal(typeof(object)).LocalIndex;
3487
            foreach (var item in members)
S
Sam Saffron 已提交
3488
            {
3489
                if (item != null)
S
Sam Saffron 已提交
3490
                {
3491
                    if (specializedConstructor == null)
3492
                        il.Emit(OpCodes.Dup); // stack is now [target][target]
S
Sam Saffron 已提交
3493 3494 3495 3496
                    Label isDbNullLabel = il.DefineLabel();
                    Label finishLabel = il.DefineLabel();

                    il.Emit(OpCodes.Ldarg_0); // stack is now [target][target][reader]
3497
                    EmitInt32(il, index); // stack is now [target][target][reader][index]
M
mgravell 已提交
3498 3499
                    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 已提交
3500
                    il.Emit(OpCodes.Callvirt, getItem); // stack is now [target][target][value-as-object]
3501 3502
                    il.Emit(OpCodes.Dup); // stack is now [target][target][value-as-object][value-as-object]
                    StoreLocal(il, valueCopyLocal);
3503
                    Type colType = reader.GetFieldType(index);
3504
                    Type memberType = item.MemberType;
M
mgravell 已提交
3505

M
mgravell 已提交
3506
                    if (memberType == typeof(char) || memberType == typeof(char?))
M
mgravell 已提交
3507
                    {
M
mgravell 已提交
3508 3509 3510 3511 3512 3513 3514 3515 3516 3517
                        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
3518

M
mgravell 已提交
3519 3520 3521 3522
                        var nullUnderlyingType = Nullable.GetUnderlyingType(memberType);
                        var unboxType = nullUnderlyingType != null && nullUnderlyingType.IsEnum ? nullUnderlyingType : memberType;

                        if (unboxType.IsEnum)
M
mgravell 已提交
3523
                        {
3524 3525
                            Type numericType = Enum.GetUnderlyingType(unboxType);
                            if(colType == typeof(string))
M
mgravell 已提交
3526
                            {
3527 3528 3529 3530 3531 3532 3533 3534
                                if (enumDeclareLocal == -1)
                                {
                                    enumDeclareLocal = il.DeclareLocal(typeof(string)).LocalIndex;
                                }
                                il.Emit(OpCodes.Castclass, typeof(string)); // stack is now [target][target][string]
                                StoreLocal(il, enumDeclareLocal); // stack is now [target][target]
                                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]
3535
                                LoadLocal(il, enumDeclareLocal); // stack is now [target][target][enum-type][string]
3536 3537 3538 3539 3540 3541 3542
                                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]
                                il.Emit(OpCodes.Unbox_Any, unboxType); // stack is now [target][target][typed-value]
                            }
                            else
                            {
                                FlexibleConvertBoxedFromHeadOfStack(il, colType, unboxType, numericType);
M
mgravell 已提交
3543
                            }
M
mgravell 已提交
3544

M
mgravell 已提交
3545
                            if (nullUnderlyingType != null)
3546
                            {
3547
                                il.Emit(OpCodes.Newobj, memberType.GetConstructor(new[] { nullUnderlyingType })); // stack is now [target][target][typed-value]
M
mgravell 已提交
3548
                            }
M
mgravell 已提交
3549
                        }
3550
                        else if (memberType.FullName == LinqBinary)
M
mgravell 已提交
3551 3552
                        {
                            il.Emit(OpCodes.Unbox_Any, typeof(byte[])); // stack is now [target][target][byte-array]
M
mgravell 已提交
3553
                            il.Emit(OpCodes.Newobj, memberType.GetConstructor(new Type[] { typeof(byte[]) }));// stack is now [target][target][binary]
M
mgravell 已提交
3554 3555 3556
                        }
                        else
                        {
3557
                            TypeCode dataTypeCode = Type.GetTypeCode(colType), unboxTypeCode = Type.GetTypeCode(unboxType);
3558
                            bool hasTypeHandler;
3559
                            if ((hasTypeHandler = typeHandlers.ContainsKey(unboxType)) || colType == unboxType || dataTypeCode == unboxTypeCode || dataTypeCode == Type.GetTypeCode(nullUnderlyingType))
3560
                            {
3561
                                if (hasTypeHandler)
3562 3563 3564 3565 3566 3567 3568 3569 3570
                                {
#pragma warning disable 618
                                    il.EmitCall(OpCodes.Call, typeof(TypeHandlerCache<>).MakeGenericType(unboxType).GetMethod("Parse"), null); // stack is now [target][target][typed-value]
#pragma warning restore 618
                                }
                                else
                                {
                                    il.Emit(OpCodes.Unbox_Any, unboxType); // stack is now [target][target][typed-value]
                                }
3571 3572 3573 3574
                            }
                            else
                            {
                                // not a direct match; need to tweak the unbox
3575
                                FlexibleConvertBoxedFromHeadOfStack(il, colType, nullUnderlyingType ?? unboxType, null);
3576 3577 3578
                                if (nullUnderlyingType != null)
                                {
                                    il.Emit(OpCodes.Newobj, unboxType.GetConstructor(new[] { nullUnderlyingType })); // stack is now [target][target][typed-value]
3579
                                }
3580

3581
                            }
3582

M
mgravell 已提交
3583
                        }
3584 3585
                    }
                    if (specializedConstructor == null)
M
mgravell 已提交
3586
                    {
3587
                        // Store the value in the property/field
3588
                        if (item.Property != null)
S
Sam Saffron 已提交
3589
                        {
3590 3591
                            if (type.IsValueType)
                            {
3592
                                il.Emit(OpCodes.Call, DefaultTypeMap.GetPropertySetter(item.Property, type)); // stack is now [target]
3593 3594 3595
                            }
                            else
                            {
3596
                                il.Emit(OpCodes.Callvirt, DefaultTypeMap.GetPropertySetter(item.Property, type)); // stack is now [target]
3597
                            }
S
Sam Saffron 已提交
3598 3599 3600
                        }
                        else
                        {
3601
                            il.Emit(OpCodes.Stfld, item.Field); // stack is now [target]
S
Sam Saffron 已提交
3602
                        }
M
mgravell 已提交
3603
                    }
3604

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

S
Sam Saffron 已提交
3607
                    il.MarkLabel(isDbNullLabel); // incoming stack: [target][target][value]
3608
                    if (specializedConstructor != null)
M
mgravell 已提交
3609
                    {
V
vosen 已提交
3610
                        il.Emit(OpCodes.Pop);
3611
                        if (item.MemberType.IsValueType)
S
Sam Saffron 已提交
3612
                        {
3613
                            int localIndex = il.DeclareLocal(item.MemberType).LocalIndex;
3614
                            LoadLocalAddress(il, localIndex);
3615
                            il.Emit(OpCodes.Initobj, item.MemberType);
3616
                            LoadLocal(il, localIndex);
S
Sam Saffron 已提交
3617 3618 3619
                        }
                        else
                        {
3620
                            il.Emit(OpCodes.Ldnull);
S
Sam Saffron 已提交
3621
                        }
M
mgravell 已提交
3622 3623 3624
                    }
                    else
                    {
3625 3626
                        il.Emit(OpCodes.Pop); // stack is now [target][target]
                        il.Emit(OpCodes.Pop); // stack is now [target]
M
mgravell 已提交
3627
                    }
S
Sam Saffron 已提交
3628

3629 3630 3631 3632
                    if (first && returnNullIfFirstMissing)
                    {
                        il.Emit(OpCodes.Pop);
                        il.Emit(OpCodes.Ldnull); // stack is now [null]
M
mgravell 已提交
3633
                        il.Emit(OpCodes.Stloc_1);
3634
                        il.Emit(OpCodes.Br, allDone);
3635 3636
                    }

S
Sam Saffron 已提交
3637 3638
                    il.MarkLabel(finishLabel);
                }
3639
                first = false;
3640
                index += 1;
S
Sam Saffron 已提交
3641
            }
S
Sam Saffron 已提交
3642 3643 3644 3645 3646 3647
            if (type.IsValueType)
            {
                il.Emit(OpCodes.Pop);
            }
            else
            {
3648 3649 3650 3651
                if (specializedConstructor != null)
                {
                    il.Emit(OpCodes.Newobj, specializedConstructor);
                }
S
Sam Saffron 已提交
3652
                il.Emit(OpCodes.Stloc_1); // stack is empty
M
Marc Gravell 已提交
3653 3654 3655 3656 3657
                if (supportInitialize)
                {
                    il.Emit(OpCodes.Ldloc_1);
                    il.EmitCall(OpCodes.Callvirt, typeof(ISupportInitialize).GetMethod("EndInit"), null);
                }
S
Sam Saffron 已提交
3658
            }
3659
            il.MarkLabel(allDone);
M
mgravell 已提交
3660 3661 3662
            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
3663
            LoadLocal(il, valueCopyLocal); // stack is Exception, index, reader, value
M
mgravell 已提交
3664 3665 3666
            il.EmitCall(OpCodes.Call, typeof(SqlMapper).GetMethod("ThrowDataException"), null);
            il.EndExceptionBlock();

3667
            il.Emit(OpCodes.Ldloc_1); // stack is [rval]
3668
            if (type.IsValueType)
S
Sam Saffron 已提交
3669 3670 3671
            {
                il.Emit(OpCodes.Box, type);
            }
M
mgravell 已提交
3672
            il.Emit(OpCodes.Ret);
S
Sam Saffron 已提交
3673

3674
            return (Func<IDataReader, object>)dm.CreateDelegate(typeof(Func<IDataReader, object>));
S
Sam Saffron 已提交
3675
        }
3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758

        private static void FlexibleConvertBoxedFromHeadOfStack(ILGenerator il, Type from, Type to, Type via)
        {
            MethodInfo op;
            if(from == (via ?? to))
            {
                il.Emit(OpCodes.Unbox_Any, to); // stack is now [target][target][typed-value]
            }
            else if ((op = GetOperator(from,to)) != null)
            {
                // this is handy for things like decimal <===> double
                il.Emit(OpCodes.Unbox_Any, from); // stack is now [target][target][data-typed-value]
                il.Emit(OpCodes.Call, op); // stack is now [target][target][typed-value]
            }
            else
            {
                bool handled = false;
                OpCode opCode = default(OpCode);
                switch (Type.GetTypeCode(from))
                {
                    case TypeCode.Boolean:
                    case TypeCode.Byte:
                    case TypeCode.SByte:
                    case TypeCode.Int16:
                    case TypeCode.UInt16:
                    case TypeCode.Int32:
                    case TypeCode.UInt32:
                    case TypeCode.Int64:
                    case TypeCode.UInt64:
                    case TypeCode.Single:
                    case TypeCode.Double:
                        handled = true;
                        switch (Type.GetTypeCode(via ?? to))
                        {
                            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;
                        }
                        break;
                }
                if (handled)
                {
                    il.Emit(OpCodes.Unbox_Any, from); // stack is now [target][target][col-typed-value]
                    il.Emit(opCode); // stack is now [target][target][typed-value]
                    if (to == typeof(bool))
                    { // 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
                {
                    il.Emit(OpCodes.Ldtoken, via ?? to); // 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, to); // stack is now [target][target][typed-value]
                }
            }            
        }

3759 3760 3761 3762 3763 3764 3765 3766
        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");
3767

3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779
        }
        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 已提交
3780

3781 3782
        private static void LoadLocal(ILGenerator il, int index)
        {
3783 3784
            if (index < 0 || index >= short.MaxValue) throw new ArgumentNullException("index");
            switch (index)
3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825
            {
                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");
3826

3827 3828 3829 3830 3831 3832 3833 3834 3835
            if (index <= 255)
            {
                il.Emit(OpCodes.Ldloca_S, (byte)index);
            }
            else
            {
                il.Emit(OpCodes.Ldloca, (short)index);
            }
        }
S
Sam Saffron 已提交
3836 3837 3838
        /// <summary>
        /// Throws a data exception, only used internally
        /// </summary>
3839 3840
        [Obsolete("Intended for internal use only")]
        public static void ThrowDataException(Exception ex, int index, IDataReader reader, object value)
M
mgravell 已提交
3841
        {
3842 3843
            Exception toThrow;
            try
M
mgravell 已提交
3844
            {
3845
                string name = "(n/a)", formattedValue = "(n/a)";
3846
                if (reader != null && index >= 0 && index < reader.FieldCount)
M
mgravell 已提交
3847
                {
3848
                    name = reader.GetName(index);
Y
Young Pay 已提交
3849
                    try
3850
                    {
3851
                        if (value == null || value is DBNull)
Y
Young Pay 已提交
3852
                        {
3853
                            formattedValue = "<null>";
Y
Young Pay 已提交
3854 3855 3856
                        }
                        else
                        {
3857
                            formattedValue = Convert.ToString(value) + " - " + Type.GetTypeCode(value.GetType());
Y
Young Pay 已提交
3858
                        }
3859
                    }
Y
Young Pay 已提交
3860
                    catch (Exception valEx)
3861
                    {
3862
                        formattedValue = valEx.Message;
3863
                    }
M
mgravell 已提交
3864
                }
3865
                toThrow = new DataException(string.Format("Error parsing column {0} ({1}={2})", index, name, formattedValue), ex);
3866 3867
            }
            catch
3868
            { // throw the **original** exception, wrapped as DataException
3869
                toThrow = new DataException(ex.Message, ex);
M
mgravell 已提交
3870
            }
3871
            throw toThrow;
M
mgravell 已提交
3872
        }
S
Sam Saffron 已提交
3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886
        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 已提交
3887 3888 3889 3890 3891 3892 3893 3894 3895 3896
                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 已提交
3897 3898
            }
        }
M
mgravell 已提交
3899

3900

3901 3902 3903 3904 3905
        /// <summary>
        /// Key used to indicate the type name associated with a DataTable
        /// </summary>
        private const string DataTableTypeNameKey = "dapper:TypeName";

3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918
        /// <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;

3919

S
Sam Saffron 已提交
3920 3921 3922
        /// <summary>
        /// The grid reader provides interfaces for reading multiple result sets from a Dapper query 
        /// </summary>
3923
        public partial class GridReader : IDisposable
M
mgravell 已提交
3924 3925 3926
        {
            private IDataReader reader;
            private IDbCommand command;
3927
            private Identity identity;
3928

3929
            internal GridReader(IDbCommand command, IDataReader reader, Identity identity, SqlMapper.IParameterCallbacks callbacks)
M
mgravell 已提交
3930 3931 3932
            {
                this.command = command;
                this.reader = reader;
3933
                this.identity = identity;
3934
                this.callbacks = callbacks;
M
mgravell 已提交
3935
            }
3936 3937 3938 3939 3940 3941

#if !CSHARP30

            /// <summary>
            /// Read the next grid of results, returned as a dynamic object
            /// </summary>
3942
            public IEnumerable<dynamic> Read(bool buffered = true)
3943
            {
M
Marc Gravell 已提交
3944
                return ReadImpl<dynamic>(typeof(DapperRow), buffered);
3945 3946 3947
            }
#endif

3948
#if CSHARP30
M
mgravell 已提交
3949 3950 3951 3952
            /// <summary>
            /// Read the next grid of results
            /// </summary>
            public IEnumerable<T> Read<T>()
3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964
            {
                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 已提交
3965
            {
M
Marc Gravell 已提交
3966
                return ReadImpl<T>(typeof(T), buffered);
M
mgravell 已提交
3967
            }
S
Sam Saffron 已提交
3968

3969 3970 3971 3972 3973 3974 3975 3976 3977 3978
            /// <summary>
            /// Read the next grid of results
            /// </summary>
#if CSHARP30
            public IEnumerable<object> Read(Type type, bool buffered)
#else
            public IEnumerable<object> Read(Type type, bool buffered = true)
#endif
            {
                if (type == null) throw new ArgumentNullException("type");
M
Marc Gravell 已提交
3979 3980 3981 3982 3983
                return ReadImpl<object>(type, buffered);
            }

            private IEnumerable<T> ReadImpl<T>(Type type, bool buffered)
            {
3984 3985 3986
                if (reader == null) throw new ObjectDisposedException(GetType().FullName, "The reader has been disposed; this can happen after all data has been consumed");
                if (consumed) throw new InvalidOperationException("Query results must be consumed in the correct order, and each result can only be consumed once");
                var typedIdentity = identity.ForGrid(type, gridIndex);
3987
                CacheInfo cache = GetCacheInfo(typedIdentity, null, true);
3988 3989 3990 3991 3992 3993 3994 3995 3996
                var deserializer = cache.Deserializer;

                int hash = GetColumnHash(reader);
                if (deserializer.Func == null || deserializer.Hash != hash)
                {
                    deserializer = new DeserializerState(hash, GetDeserializer(type, reader, 0, -1, false));
                    cache.Deserializer = deserializer;
                }
                consumed = true;
M
Marc Gravell 已提交
3997
                var result = ReadDeferred<T>(gridIndex, deserializer.Func, typedIdentity);
3998 3999 4000
                return buffered ? result.ToList() : result;
            }

M
Marc Gravell 已提交
4001

4002
            private IEnumerable<TReturn> MultiReadInternal<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(Delegate func, string splitOn)
4003 4004 4005 4006 4007 4008
            {
                var identity = this.identity.ForGrid(typeof(TReturn), new Type[] { 
                    typeof(TFirst), 
                    typeof(TSecond),
                    typeof(TThird),
                    typeof(TFourth),
4009 4010 4011
                    typeof(TFifth),
                    typeof(TSixth),
                    typeof(TSeventh)
4012 4013 4014
                }, gridIndex);
                try
                {
4015
                    foreach (var r in SqlMapper.MultiMapImpl<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(null, default(CommandDefinition), func, splitOn, reader, identity, false))
4016 4017 4018 4019 4020 4021 4022 4023 4024 4025
                    {
                        yield return r;
                    }
                }
                finally
                {
                    NextResult();
                }
            }

4026
#if CSHARP30
S
Sam Saffron 已提交
4027 4028 4029
            /// <summary>
            /// Read multiple objects from a single recordset on the grid
            /// </summary>
4030
            public IEnumerable<TReturn> Read<TFirst, TSecond, TReturn>(Func<TFirst, TSecond, TReturn> func, string splitOn)
4031 4032 4033 4034 4035 4036 4037
            {
                return Read<TFirst, TSecond, TReturn>(func, splitOn, true);
            }
#endif
            /// <summary>
            /// Read multiple objects from a single recordset on the grid
            /// </summary>
4038
#if CSHARP30
4039
            public IEnumerable<TReturn> Read<TFirst, TSecond, TReturn>(Func<TFirst, TSecond, TReturn> func, string splitOn, bool buffered)
4040
#else
4041
            public IEnumerable<TReturn> Read<TFirst, TSecond, TReturn>(Func<TFirst, TSecond, TReturn> func, string splitOn = "id", bool buffered = true)
4042 4043
#endif
            {
4044
                var result = MultiReadInternal<TFirst, TSecond, DontMap, DontMap, DontMap, DontMap, DontMap, TReturn>(func, splitOn);
4045
                return buffered ? result.ToList() : result;
4046 4047
            }

4048
#if CSHARP30
S
Sam Saffron 已提交
4049 4050 4051
            /// <summary>
            /// Read multiple objects from a single recordset on the grid
            /// </summary>
4052
            public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TReturn>(Func<TFirst, TSecond, TThird, TReturn> func, string splitOn)
4053 4054 4055 4056 4057 4058 4059
            {
                return Read<TFirst, TSecond, TThird, TReturn>(func, splitOn, true);
            }
#endif
            /// <summary>
            /// Read multiple objects from a single recordset on the grid
            /// </summary>
4060
#if CSHARP30
4061
            public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TReturn>(Func<TFirst, TSecond, TThird, TReturn> func, string splitOn, bool buffered)
4062
#else
4063
            public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TReturn>(Func<TFirst, TSecond, TThird, TReturn> func, string splitOn = "id", bool buffered = true)
4064 4065
#endif
            {
4066
                var result = MultiReadInternal<TFirst, TSecond, TThird, DontMap, DontMap, DontMap, DontMap, TReturn>(func, splitOn);
4067
                return buffered ? result.ToList() : result;
4068 4069
            }

4070
#if CSHARP30
S
Sam Saffron 已提交
4071 4072 4073
            /// <summary>
            /// Read multiple objects from a single record set on the grid
            /// </summary>
4074
            public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TFourth, TReturn>(Func<TFirst, TSecond, TThird, TFourth, TReturn> func, string splitOn)
4075 4076 4077 4078 4079 4080 4081 4082
            {
                return Read<TFirst, TSecond, TThird, TFourth, TReturn>(func, splitOn, true);
            }
#endif

            /// <summary>
            /// Read multiple objects from a single record set on the grid
            /// </summary>
4083
#if CSHARP30
4084
            public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TFourth, TReturn>(Func<TFirst, TSecond, TThird, TFourth, TReturn> func, string splitOn, bool buffered)
4085
#else
4086
            public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TFourth, TReturn>(Func<TFirst, TSecond, TThird, TFourth, TReturn> func, string splitOn = "id", bool buffered = true)
4087 4088
#endif
            {
4089
                var result = MultiReadInternal<TFirst, TSecond, TThird, TFourth, DontMap, DontMap, DontMap, TReturn>(func, splitOn);
4090
                return buffered ? result.ToList() : result;
4091 4092
            }

4093 4094


4095
#if !CSHARP30
S
Sam Saffron 已提交
4096 4097 4098
            /// <summary>
            /// Read multiple objects from a single record set on the grid
            /// </summary>
4099
            public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn> func, string splitOn = "id", bool buffered = true)
4100
            {
4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117
                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);
4118
                return buffered ? result.ToList() : result;
4119 4120
            }
#endif
S
Sam Saffron 已提交
4121

4122
            private IEnumerable<T> ReadDeferred<T>(int index, Func<IDataReader, object> deserializer, Identity typedIdentity)
M
mgravell 已提交
4123 4124 4125 4126 4127
            {
                try
                {
                    while (index == gridIndex && reader.Read())
                    {
4128
                        yield return (T)deserializer(reader);
M
mgravell 已提交
4129 4130 4131 4132 4133 4134 4135 4136 4137 4138
                    }
                }
                finally // finally so that First etc progresses things even when multiple rows
                {
                    if (index == gridIndex)
                    {
                        NextResult();
                    }
                }
            }
4139
            private int gridIndex, readCount;
M
mgravell 已提交
4140
            private bool consumed;
4141
            private SqlMapper.IParameterCallbacks callbacks;
4142

M
Marc Gravell 已提交
4143 4144 4145
            /// <summary>
            /// Has the underlying reader been consumed?
            /// </summary>
4146 4147 4148 4149 4150 4151 4152
            public bool IsConsumed
            {
                get
                {
                    return consumed;
                }
            }
M
mgravell 已提交
4153 4154 4155 4156
            private void NextResult()
            {
                if (reader.NextResult())
                {
4157
                    readCount++;
M
mgravell 已提交
4158 4159 4160 4161 4162
                    gridIndex++;
                    consumed = false;
                }
                else
                {
4163 4164 4165 4166
                    // happy path; close the reader cleanly - no
                    // need for "Cancel" etc
                    reader.Dispose();
                    reader = null;
4167
                    if (callbacks != null) callbacks.OnCompleted();
M
mgravell 已提交
4168 4169 4170
                    Dispose();
                }
            }
S
Sam Saffron 已提交
4171 4172 4173
            /// <summary>
            /// Dispose the grid, closing and disposing both the underlying reader and command.
            /// </summary>
M
mgravell 已提交
4174 4175 4176 4177
            public void Dispose()
            {
                if (reader != null)
                {
4178
                    if (!reader.IsClosed && command != null) command.Cancel();
M
mgravell 已提交
4179 4180 4181 4182 4183 4184 4185 4186 4187 4188
                    reader.Dispose();
                    reader = null;
                }
                if (command != null)
                {
                    command.Dispose();
                    command = null;
                }
            }
        }
4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200

        /// <summary>
        /// Used to pass a DataTable as a TableValuedParameter
        /// </summary>
        public static ICustomQueryParameter AsTableValuedParameter(this DataTable table, string typeName
#if !CSHARP30
            = null
#endif
            )
        {
            return new TableValuedParameter(table, typeName);
        }
4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222

        /// <summary>
        /// Associate a DataTable with a type name
        /// </summary>
        public static void SetTypeName(this DataTable table, string typeName)
        {
            if (table != null)
            {
                if (string.IsNullOrEmpty(typeName))
                    table.ExtendedProperties.Remove(DataTableTypeNameKey);
                else
                    table.ExtendedProperties[DataTableTypeNameKey] = typeName;
            }
        }

        /// <summary>
        /// Fetch the type name associated with a DataTable
        /// </summary>
        public static string GetTypeName(this DataTable table)
        {
            return table == null ? null : table.ExtendedProperties[DataTableTypeNameKey] as string;
        }
S
Sam Saffron 已提交
4223
    }
S
Sam Saffron 已提交
4224 4225 4226 4227

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

4233
        Dictionary<string, ParamInfo> parameters = new Dictionary<string, ParamInfo>();
4234
        List<object> templates;
S
Sam Saffron 已提交
4235

4236 4237 4238 4239 4240 4241 4242 4243 4244
        object SqlMapper.IParameterLookup.this[string member]
        {
            get
            {
                ParamInfo param;
                return parameters.TryGetValue(member, out param) ? param.Value : null;
            }
        }

4245
        partial class ParamInfo
S
Sam Saffron 已提交
4246 4247 4248 4249 4250 4251 4252
        {
            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; }
4253 4254 4255
            internal Action<object, DynamicParameters> OutputCallback { get; set; }
            internal object OutputTarget { get; set; }
            internal bool CameFromTemplate { get; set; }
S
Sam Saffron 已提交
4256 4257
        }

S
Sam Saffron 已提交
4258 4259 4260
        /// <summary>
        /// construct a dynamic parameter bag
        /// </summary>
4261 4262 4263 4264
        public DynamicParameters()
        {
            RemoveUnused = true;
        }
4265

S
Sam Saffron 已提交
4266 4267 4268
        /// <summary>
        /// construct a dynamic parameter bag
        /// </summary>
4269
        /// <param name="template">can be an anonymous type or a DynamicParameters bag</param>
4270 4271
        public DynamicParameters(object template)
        {
4272
            RemoveUnused = true;
4273
            AddDynamicParams(template);
4274 4275 4276 4277
        }

        /// <summary>
        /// Append a whole object full of params to the dynamic
4278
        /// EG: AddDynamicParams(new {A = 1, B = 2}) // will add property A and B to the dynamic
4279 4280 4281 4282
        /// </summary>
        /// <param name="param"></param>
        public void AddDynamicParams(
#if CSHARP30
4283
object param
4284
#else
4285
dynamic param
4286
#endif
4287
)
4288
        {
4289
            var obj = param as object;
4290
            if (obj != null)
4291 4292 4293 4294
            {
                var subDynamic = obj as DynamicParameters;
                if (subDynamic == null)
                {
4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311
                    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
                        }
                    }
4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324
                }
                else
                {
                    if (subDynamic.parameters != null)
                    {
                        foreach (var kvp in subDynamic.parameters)
                        {
                            parameters.Add(kvp.Key, kvp.Value);
                        }
                    }

                    if (subDynamic.templates != null)
                    {
4325
                        templates = templates ?? new List<object>();
4326 4327 4328 4329 4330 4331
                        foreach (var t in subDynamic.templates)
                        {
                            templates.Add(t);
                        }
                    }
                }
4332 4333 4334
            }
        }

S
Sam Saffron 已提交
4335 4336 4337 4338 4339 4340 4341 4342
        /// <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 已提交
4343 4344
        public void Add(
#if CSHARP30
4345
string name, object value, DbType? dbType, ParameterDirection? direction, int? size
M
mgravell 已提交
4346
#else
4347 4348 4349
string name, object value = null, DbType? dbType = null, ParameterDirection? direction = null, int? size = null
#endif
)
S
Sam Saffron 已提交
4350
        {
4351
            parameters[Clean(name)] = new ParamInfo() { Name = name, Value = value, ParameterDirection = direction ?? ParameterDirection.Input, DbType = dbType, Size = size };
S
Sam Saffron 已提交
4352 4353
        }

4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367
        static string Clean(string name)
        {
            if (!string.IsNullOrEmpty(name))
            {
                switch (name[0])
                {
                    case '@':
                    case ':':
                    case '?':
                        return name.Substring(1);
                }
            }
            return name;
        }
S
Sam Saffron 已提交
4368

4369
        void SqlMapper.IDynamicParameters.AddParameters(IDbCommand command, SqlMapper.Identity identity)
4370 4371 4372 4373
        {
            AddParameters(command, identity);
        }

4374 4375 4376 4377 4378
        /// <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; }

4379 4380 4381 4382 4383 4384
        /// <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 已提交
4385
        {
4386
            var literals = SqlMapper.GetLiteralTokens(identity.sql);
4387

4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398
            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))
                        {
4399
                            appender = SqlMapper.CreateParamInfoGenerator(newIdent, true, RemoveUnused, literals);
4400 4401 4402 4403 4404 4405
                            paramReaderCache[newIdent] = appender;
                        }
                    }

                    appender(command, template);
                }
4406 4407 4408 4409 4410

                // The parameters were added to the command, but not the 
                // DynamicParameters until now.
                foreach (IDbDataParameter param in command.Parameters)
                {
D
Derek Gray 已提交
4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426
                    // If someone makes a DynamicParameters with a template,
                    // then explicitly adds a parameter of a matching name,
                    // it will already exist in 'parameters'.
                    if (!parameters.ContainsKey(param.ParameterName)) 
                    { 
                        parameters.Add(param.ParameterName, new ParamInfo
                        {
                            AttachedParam = param,
                            CameFromTemplate = true,
                            DbType = param.DbType,
                            Name = param.ParameterName,
                            ParameterDirection = param.Direction,
                            Size = param.Size,
                            Value = param.Value
                        });
                    }
4427 4428 4429
                }

                // Now that the parameters are added to the command, let's place our output callbacks
4430 4431
                var tmp = outputCallbacks;
                if (tmp != null)
4432
                {
4433 4434 4435 4436
                    foreach (var generator in tmp)
                    {
                        generator();
                    }
4437
                }
4438 4439
            }

4440
            foreach (var param in parameters.Values)
S
Sam Saffron 已提交
4441
            {
4442 4443
                if (param.CameFromTemplate) continue;

4444 4445
                var dbType = param.DbType;
                var val = param.Value;
4446
                string name = Clean(param.Name);
4447
                var isCustomQueryParameter = val is SqlMapper.ICustomQueryParameter;
4448

4449 4450
                SqlMapper.ITypeHandler handler = null;
                if (dbType == null && val != null && !isCustomQueryParameter) dbType = SqlMapper.LookupDbType(val.GetType(), name, out handler);
4451 4452
                if (dbType == DynamicParameters.EnumerableMultiParameter)
                {
4453 4454 4455
#pragma warning disable 612, 618
                    SqlMapper.PackListParameters(command, name, val);
#pragma warning restore 612, 618
4456
                }
4457 4458 4459 4460
                else if (isCustomQueryParameter)
                {
                    ((SqlMapper.ICustomQueryParameter)val).AddParameter(command, name);
                }
4461
                else
S
Sam Saffron 已提交
4462
                {
4463 4464 4465 4466

                    bool add = !command.Parameters.Contains(name);
                    IDbDataParameter p;
                    if (add)
S
Sam Saffron 已提交
4467
                    {
4468 4469
                        p = command.CreateParameter();
                        p.ParameterName = name;
S
Sam Saffron 已提交
4470
                    }
4471 4472 4473 4474
                    else
                    {
                        p = (IDbDataParameter)command.Parameters[name];
                    }
4475 4476

                    p.Direction = param.ParameterDirection;
4477 4478 4479
                    if (handler == null)
                    {
                        p.Value = val ?? DBNull.Value;
4480
                        if (dbType != null && p.DbType != dbType)
4481
                        {
4482
                            p.DbType = dbType.Value;
4483
                        }
4484 4485 4486
                        var s = val as string;
                        if (s != null)
                        {
4487
                            if (s.Length <= DbString.DefaultLength)
4488
                            {
4489
                                p.Size = DbString.DefaultLength;
4490 4491 4492 4493 4494 4495
                            }
                        }
                        if (param.Size != null)
                        {
                            p.Size = param.Size.Value;
                        }                        
4496
                    }
4497
                    else
4498
                    {
4499 4500 4501
                        if (dbType != null) p.DbType = dbType.Value;
                        if (param.Size != null) p.Size = param.Size.Value;
                        handler.SetValue(p, val ?? DBNull.Value);
4502
                    }
4503

4504 4505 4506 4507 4508
                    if (add)
                    {
                        command.Parameters.Add(p);
                    }
                    param.AttachedParam = p;
S
Sam Saffron 已提交
4509 4510
                }
            }
4511

4512 4513
            // note: most non-priveleged implementations would use: this.ReplaceLiterals(command);
            if(literals.Count != 0) SqlMapper.ReplaceLiterals(this, command, literals);
S
Sam Saffron 已提交
4514 4515
        }

S
Sam Saffron 已提交
4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527
        /// <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 已提交
4528 4529 4530 4531 4532 4533
        /// <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 已提交
4534
        public T Get<T>(string name)
S
Sam Saffron 已提交
4535
        {
4536 4537 4538 4539 4540 4541 4542 4543 4544 4545
            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 已提交
4546
        }
4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566

        /// <summary>
        /// Allows you to automatically populate a target property/field from output parameters. It actually
        /// creates an InputOutput parameter, so you can still pass data in. 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="target">The object whose property/field you wish to populate.</param>
        /// <param name="expression">A MemberExpression targeting a property/field of the target (or descendant thereof.)</param>
        /// <param name="dbType"></param>
        /// <param name="size">The size to set on the parameter. Defaults to 0, or DbString.DefaultLength in case of strings.</param>
        /// <returns>The DynamicParameters instance</returns>
#if CSHARP30
        public DynamicParameters Output<T>(T target, Expression<Func<T, object>> expression, DbType? dbType, int? size)
#else
        public DynamicParameters Output<T>(T target, Expression<Func<T, object>> expression, DbType? dbType = null, int? size = null)
#endif
        {
            var failMessage = "Expression must be a property/field chain off of a(n) {0} instance";
            failMessage = string.Format(failMessage, typeof(T).Name);
            Action @throw = () => { throw new InvalidOperationException(failMessage); };
4567

4568 4569 4570 4571 4572
            // Is it even a MemberExpression?
            var lastMemberAccess = expression.Body as MemberExpression;

            if (lastMemberAccess == null ||
                (lastMemberAccess.Member.MemberType != MemberTypes.Property &&
4573
                lastMemberAccess.Member.MemberType != MemberTypes.Field))
4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606
            {
                if (expression.Body.NodeType == ExpressionType.Convert &&
                    expression.Body.Type == typeof(object) &&
                    ((UnaryExpression)expression.Body).Operand is MemberExpression)
                {
                    // It's got to be unboxed
                    lastMemberAccess = (MemberExpression)((UnaryExpression)expression.Body).Operand;
                }
                else @throw();
            }

            // Does the chain consist of MemberExpressions leading to a ParameterExpression of type T?
            MemberExpression diving = lastMemberAccess;
            ParameterExpression constant = null;
            // Retain a list of member names and the member expressions so we can rebuild the chain.
            List<string> names = new List<string>();
            List<MemberExpression> chain = new List<MemberExpression>();

            do
            {
                // Insert the names in the right order so expression 
                // "Post.Author.Name" becomes parameter "PostAuthorName"
                names.Insert(0, diving.Member.Name);
                chain.Insert(0, diving);

                constant = diving.Expression as ParameterExpression;
                diving = diving.Expression as MemberExpression;

                if (constant != null &&
                    constant.Type == typeof(T))
                {
                    break;
                }
4607
                else if (diving == null ||
4608 4609 4610 4611 4612
                    (diving.Member.MemberType != MemberTypes.Property &&
                    diving.Member.MemberType != MemberTypes.Field))
                {
                    @throw();
                }
4613
            }
4614 4615 4616 4617 4618
            while (diving != null);

            var dynamicParamName = string.Join(string.Empty, names.ToArray());

            // Before we get all emitty...
4619 4620 4621 4622 4623 4624
            var lookup = string.Join("|", names.ToArray());

            var cache = CachedOutputSetters<T>.Cache;
            var setter = (Action<object, DynamicParameters>)cache[lookup];

            if (setter != null) goto MAKECALLBACK;
4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670

            // Come on let's build a method, let's build it, let's build it now!
            var dm = new DynamicMethod(string.Format("ExpressionParam{0}", Guid.NewGuid()), null, new[] { typeof(object), this.GetType() }, true);
            var il = dm.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0); // [object]
            il.Emit(OpCodes.Castclass, typeof(T));    // [T]

            // Count - 1 to skip the last member access
            var i = 0;
            for (; i < (chain.Count - 1); i++)
            {
                var member = chain[0].Member;

                if (member.MemberType == MemberTypes.Property)
                {
                    var get = ((PropertyInfo)member).GetGetMethod(true);
                    il.Emit(OpCodes.Callvirt, get); // [Member{i}]
                }
                else // Else it must be a field!
                {
                    il.Emit(OpCodes.Ldfld, ((FieldInfo)member)); // [Member{i}]
                }
            }

            var paramGetter = this.GetType().GetMethod("Get", new Type[] { typeof(string) }).MakeGenericMethod(lastMemberAccess.Type);

            il.Emit(OpCodes.Ldarg_1); // [target] [DynamicParameters]
            il.Emit(OpCodes.Ldstr, dynamicParamName); // [target] [DynamicParameters] [ParamName]
            il.Emit(OpCodes.Callvirt, paramGetter); // [target] [value], it's already typed thanks to generic method
            
            // GET READY
            var lastMember = lastMemberAccess.Member;
            if (lastMember.MemberType == MemberTypes.Property)
            {
                var set = ((PropertyInfo)lastMember).GetSetMethod(true);
                il.Emit(OpCodes.Callvirt, set); // SET
            }
            else
            {
                il.Emit(OpCodes.Stfld, ((FieldInfo)lastMember)); // SET
            }

            il.Emit(OpCodes.Ret); // GO

            setter = (Action<object, DynamicParameters>)dm.CreateDelegate(typeof(Action<object, DynamicParameters>));
4671
            lock (cache)
4672
            {
4673
                cache[lookup] = setter;
4674 4675 4676 4677
            }

            // Queue the preparation to be fired off when adding parameters to the DbCommand
            MAKECALLBACK:
4678
            (outputCallbacks ?? (outputCallbacks = new List<Action>())).Add(() =>
4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711
            {
                // Finally, prep the parameter and attach the callback to it
                ParamInfo parameter;
                var targetMemberType = lastMemberAccess.Type;
                int sizeToSet = (!size.HasValue && targetMemberType == typeof(string)) ? DbString.DefaultLength : size ?? 0;

                if (this.parameters.TryGetValue(dynamicParamName, out parameter))
                {
                    parameter.ParameterDirection = parameter.AttachedParam.Direction = ParameterDirection.InputOutput;

                    if (parameter.AttachedParam.Size == 0)
                    {
                        parameter.Size = parameter.AttachedParam.Size = sizeToSet;
                    }
                }
                else
                {
                    SqlMapper.ITypeHandler handler;
                    dbType = (!dbType.HasValue) ? SqlMapper.LookupDbType(targetMemberType, targetMemberType.Name, out handler) : dbType;

                    // CameFromTemplate property would not apply here because this new param
                    // Still needs to be added to the command
                    this.Add(dynamicParamName, expression.Compile().Invoke(target), null, ParameterDirection.InputOutput, sizeToSet);
                }

                parameter = this.parameters[dynamicParamName];
                parameter.OutputCallback = setter;
                parameter.OutputTarget = target;
            });

            return this;
        }

4712
        private List<Action> outputCallbacks;
4713 4714 4715

        private readonly Dictionary<string, Action<object, DynamicParameters>> cachedOutputSetters = new Dictionary<string,Action<object,DynamicParameters>>();

4716 4717 4718 4719
        internal static class CachedOutputSetters<T>
        {
            public static readonly Hashtable Cache = new Hashtable();
        }
4720

4721
        void SqlMapper.IParameterCallbacks.OnCompleted()
4722 4723 4724 4725 4726 4727
        {
            foreach (var param in (from p in parameters select p.Value))
            {
                if (param.OutputCallback != null) param.OutputCallback(param.OutputTarget, this);
            }
        }
S
Sam Saffron 已提交
4728
    }
S
Sam Saffron 已提交
4729

4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742
    sealed class DataTableHandler : Dapper.SqlMapper.ITypeHandler
    {
        public object Parse(Type destinationType, object value)
        {
            throw new NotImplementedException();
        }

        public void SetValue(IDbDataParameter parameter, object value)
        {
            TableValuedParameter.Set(parameter, value as DataTable, null);
        }
    }

4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762
    /// <summary>
    /// Used to pass a DataTable as a TableValuedParameter
    /// </summary>
    sealed partial class TableValuedParameter : Dapper.SqlMapper.ICustomQueryParameter
    {
        private readonly DataTable table;
        private readonly string typeName;

        /// <summary>
        /// Create a new instance of TableValuedParameter
        /// </summary>
        public TableValuedParameter(DataTable table) : this(table, null) { }
        /// <summary>
        /// Create a new instance of TableValuedParameter
        /// </summary>
        public TableValuedParameter(DataTable table, string typeName)
        {
            this.table = table;
            this.typeName = typeName;
        }
4763 4764 4765 4766 4767 4768 4769 4770 4771 4772
        static readonly Action<System.Data.SqlClient.SqlParameter, string> setTypeName;
        static TableValuedParameter()
        {
            var prop = typeof(System.Data.SqlClient.SqlParameter).GetProperty("TypeName", BindingFlags.Instance | BindingFlags.Public);
            if(prop != null && prop.PropertyType == typeof(string) && prop.CanWrite)
            {
                setTypeName = (Action<System.Data.SqlClient.SqlParameter, string>)
                    Delegate.CreateDelegate(typeof(Action<System.Data.SqlClient.SqlParameter, string>), prop.GetSetMethod());
            }
        }
4773 4774
        void SqlMapper.ICustomQueryParameter.AddParameter(IDbCommand command, string name)
        {
4775 4776
            var param = command.CreateParameter();
            param.ParameterName = name;
4777 4778 4779 4780 4781 4782 4783 4784 4785 4786
            Set(param, table, typeName);
            command.Parameters.Add(param);
        }
        internal static void Set(IDbDataParameter parameter, DataTable table, string typeName)
        {
            parameter.Value = (object)table ?? DBNull.Value;
            if (string.IsNullOrEmpty(typeName) && table != null)
            {
                typeName = SqlMapper.GetTypeName(table);
            }
4787 4788
            if (!string.IsNullOrEmpty(typeName))
            {
4789
                var sqlParam = parameter as System.Data.SqlClient.SqlParameter;
4790 4791
                if (sqlParam != null)
                {
4792
                    if (setTypeName != null) setTypeName(sqlParam, typeName);
4793 4794 4795
                    sqlParam.SqlDbType = SqlDbType.Structured;
                }
            }
4796 4797
        }
    }
S
Sam Saffron 已提交
4798 4799 4800
    /// <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>
4801
    sealed partial class DbString : Dapper.SqlMapper.ICustomQueryParameter
M
mgravell 已提交
4802
    {
4803 4804 4805 4806 4807 4808 4809
        /// <summary>
        /// A value to set the default value of strings
        /// going through Dapper. Default is 4000, any value larger than this
        /// field will not have the default value applied.
        /// </summary>
        public const int DefaultLength = 4000;

S
Sam Saffron 已提交
4810 4811 4812
        /// <summary>
        /// Create a new DbString
        /// </summary>
M
mgravell 已提交
4813
        public DbString() { Length = -1; }
S
Sam Saffron 已提交
4814 4815 4816
        /// <summary>
        /// Ansi vs Unicode 
        /// </summary>
M
mgravell 已提交
4817
        public bool IsAnsi { get; set; }
S
Sam Saffron 已提交
4818 4819 4820
        /// <summary>
        /// Fixed length 
        /// </summary>
M
mgravell 已提交
4821
        public bool IsFixedLength { get; set; }
S
Sam Saffron 已提交
4822 4823 4824
        /// <summary>
        /// Length of the string -1 for max
        /// </summary>
M
mgravell 已提交
4825
        public int Length { get; set; }
S
Sam Saffron 已提交
4826 4827 4828
        /// <summary>
        /// The value of the string
        /// </summary>
M
mgravell 已提交
4829
        public string Value { get; set; }
S
Sam Saffron 已提交
4830 4831 4832 4833 4834
        /// <summary>
        /// Add the parameter to the command... internal use only
        /// </summary>
        /// <param name="command"></param>
        /// <param name="name"></param>
M
mgravell 已提交
4835 4836 4837 4838 4839 4840 4841 4842 4843
        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;
4844
            if (Length == -1 && Value != null && Value.Length <= DefaultLength)
M
mgravell 已提交
4845
            {
4846
                param.Size = DefaultLength;
M
mgravell 已提交
4847 4848 4849 4850 4851 4852 4853 4854 4855
            }
            else
            {
                param.Size = Length;
            }
            param.DbType = IsAnsi ? (IsFixedLength ? DbType.AnsiStringFixedLength : DbType.AnsiString) : (IsFixedLength ? DbType.StringFixedLength : DbType.String);
            command.Parameters.Add(param);
        }
    }
4856

4857 4858 4859 4860 4861
    /// <summary>
    /// Handles variances in features per DBMS
    /// </summary>
    partial class FeatureSupport
    {
4862 4863 4864
        private static readonly FeatureSupport
            @default = new FeatureSupport(false),
            postgres = new FeatureSupport(true);
4865

4866 4867 4868 4869 4870
        /// <summary>
        /// Gets the featureset based on the passed connection
        /// </summary>
        public static FeatureSupport Get(IDbConnection connection)
        {
4871 4872 4873 4874 4875 4876 4877
            string name = connection == null ? null : connection.GetType().Name;
            if (string.Equals(name, "npgsqlconnection", StringComparison.InvariantCultureIgnoreCase)) return postgres;
            return @default;
        }
        private FeatureSupport(bool arrays)
        {
            Arrays = arrays;
4878 4879 4880 4881
        }
        /// <summary>
        /// True if the db supports array columns e.g. Postgresql
        /// </summary>
4882
        public bool Arrays { get; private set; }
4883
    }
4884

4885 4886 4887
    /// <summary>
    /// Represents simple memeber map for one of target parameter or property or field to source DataReader column
    /// </summary>
4888
    sealed partial class SimpleMemberMap : SqlMapper.IMemberMap
4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001
    {
        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>
5002
    sealed partial class DefaultTypeMap : SqlMapper.ITypeMap
5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025
    {
        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) :
5026 5027 5028 5029 5030 5031 5032
                propertyInfo.DeclaringType.GetProperty(
                   propertyInfo.Name,
                   BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
                   Type.DefaultBinder,
                   propertyInfo.PropertyType,
                   propertyInfo.GetIndexParameters().Select(p => p.ParameterType).ToArray(),
                   null).GetSetMethod(true);
5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107
        }

        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))
5108 5109 5110 5111 5112 5113 5114
               ?? _properties.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.OrdinalIgnoreCase));

            if (property == null && MatchNamesWithUnderscores)
            {
                property = _properties.FirstOrDefault(p => string.Equals(p.Name, columnName.Replace("_", ""), StringComparison.Ordinal))
                    ?? _properties.FirstOrDefault(p => string.Equals(p.Name, columnName.Replace("_", ""), StringComparison.OrdinalIgnoreCase));
            }
5115 5116 5117 5118 5119

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

            var field = _fields.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.Ordinal))
5120 5121 5122 5123 5124 5125 5126
               ?? _fields.FirstOrDefault(p => string.Equals(p.Name, columnName, StringComparison.OrdinalIgnoreCase));

            if (field == null && MatchNamesWithUnderscores)
            {
                field = _fields.FirstOrDefault(p => string.Equals(p.Name, columnName.Replace("_", ""), StringComparison.Ordinal))
                    ?? _fields.FirstOrDefault(p => string.Equals(p.Name, columnName.Replace("_", ""), StringComparison.OrdinalIgnoreCase));
            }
5127 5128 5129 5130 5131 5132

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

            return null;
        }
5133 5134 5135 5136
        /// <summary>
        /// Should column names like User_Id be allowed to match properties/fields like UserId ?
        /// </summary>
        public static bool MatchNamesWithUnderscores { get; set; }
5137 5138
    }

5139 5140
    

5141 5142 5143
    /// <summary>
    /// Implements custom property mapping by user provided criteria (usually presence of some custom attribute with column to member mapping)
    /// </summary>
5144
    sealed partial class CustomPropertyTypeMap : SqlMapper.ITypeMap
5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184
    {
        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)
        {
5185
            throw new NotSupportedException();
5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199
        }

        /// <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;
        }
    }

5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210
    // 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
    {
5211

5212 5213 5214 5215
    }

    public partial class DbString
    {
5216

5217 5218
    }

5219
    
5220 5221
    public partial class SimpleMemberMap
    {
5222

5223
    }
5224

5225 5226
    public partial class DefaultTypeMap
    {
5227

5228 5229 5230 5231
    }

    public partial class CustomPropertyTypeMap
    {
5232

5233 5234
    }

5235 5236 5237 5238
    public partial class FeatureSupport
    {

    }
5239 5240

#endif
5241

5242
}