Commit 0444094f authored by Marc Gravell's avatar Marc Gravell

Manual rollback while I figure out some DapperTable questions

parent 1e1c7157
...@@ -5,7 +5,6 @@ ...@@ -5,7 +5,6 @@
Note: to build on C# 3.0 + .NET 3.5, include the CSHARP30 compiler symbol (and yes, 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). I know the difference between language and runtime versions; this is a compromise).
*/ */
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
...@@ -19,7 +18,6 @@ ...@@ -19,7 +18,6 @@
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Diagnostics; using System.Diagnostics;
namespace Dapper namespace Dapper
{ {
/// <summary> /// <summary>
...@@ -259,7 +257,7 @@ public static void PurgeQueryCache() ...@@ -259,7 +257,7 @@ public static void PurgeQueryCache()
static readonly System.Collections.Concurrent.ConcurrentDictionary<Identity, CacheInfo> _queryCache = new System.Collections.Concurrent.ConcurrentDictionary<Identity, CacheInfo>(); static readonly System.Collections.Concurrent.ConcurrentDictionary<Identity, CacheInfo> _queryCache = new System.Collections.Concurrent.ConcurrentDictionary<Identity, CacheInfo>();
private static void SetQueryCache(Identity key, CacheInfo value) private static void SetQueryCache(Identity key, CacheInfo value)
{ {
if(Interlocked.Increment(ref collect)==COLLECT_PER_ITEMS) if (Interlocked.Increment(ref collect) == COLLECT_PER_ITEMS)
{ {
CollectCacheGarbage(); CollectCacheGarbage();
} }
...@@ -290,7 +288,7 @@ private static void CollectCacheGarbage() ...@@ -290,7 +288,7 @@ private static void CollectCacheGarbage()
private static int collect; private static int collect;
private static bool TryGetQueryCache(Identity key, out CacheInfo value) private static bool TryGetQueryCache(Identity key, out CacheInfo value)
{ {
if(_queryCache.TryGetValue(key, out value)) if (_queryCache.TryGetValue(key, out value))
{ {
value.RecordHit(); value.RecordHit();
return true; return true;
...@@ -343,16 +341,17 @@ public static int GetCachedSQLCount() ...@@ -343,16 +341,17 @@ public static int GetCachedSQLCount()
/// Deep diagnostics only: find any hash collisions in the cache /// Deep diagnostics only: find any hash collisions in the cache
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public static IEnumerable<Tuple<int,int>> GetHashCollissions() public static IEnumerable<Tuple<int, int>> GetHashCollissions()
{ {
var counts = new Dictionary<int, int>(); var counts = new Dictionary<int, int>();
foreach(var key in _queryCache.Keys) foreach (var key in _queryCache.Keys)
{ {
int count; int count;
if(!counts.TryGetValue(key.hashCode, out count)) if (!counts.TryGetValue(key.hashCode, out count))
{ {
counts.Add(key.hashCode, 1); counts.Add(key.hashCode, 1);
} else }
else
{ {
counts[key.hashCode] = count + 1; counts[key.hashCode] = count + 1;
} }
...@@ -703,7 +702,7 @@ public static GridReader QueryMultiple(this IDbConnection cnn, string sql, objec ...@@ -703,7 +702,7 @@ public static GridReader QueryMultiple(this IDbConnection cnn, string sql, objec
// nice and simple // nice and simple
if ((object)param != null) if ((object)param != null)
{ {
identity = new Identity(sql, commandType, cnn, null, (object) param == null ? null : ((object) param).GetType(), null); identity = new Identity(sql, commandType, cnn, null, (object)param == null ? null : ((object)param).GetType(), null);
info = GetCacheInfo(identity); info = GetCacheInfo(identity);
} }
return ExecuteCommand(cnn, transaction, sql, (object)param == null ? null : info.ParamReader, (object)param, commandTimeout, commandType); return ExecuteCommand(cnn, transaction, sql, (object)param == null ? null : info.ParamReader, (object)param, commandTimeout, commandType);
...@@ -714,7 +713,7 @@ public static GridReader QueryMultiple(this IDbConnection cnn, string sql, objec ...@@ -714,7 +713,7 @@ public static GridReader QueryMultiple(this IDbConnection cnn, string sql, objec
/// </summary> /// </summary>
public static IEnumerable<dynamic> Query(this IDbConnection cnn, string sql, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null) public static IEnumerable<dynamic> Query(this IDbConnection cnn, string sql, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
{ {
return Query<DapperRow>(cnn, sql, param as object, transaction, buffered, commandTimeout, commandType); return Query<FastExpando>(cnn, sql, param as object, transaction, buffered, commandTimeout, commandType);
} }
#else #else
/// <summary> /// <summary>
...@@ -1046,7 +1045,7 @@ partial class DontMap { } ...@@ -1046,7 +1045,7 @@ partial class DontMap { }
private static Func<IDataReader, TReturn> GenerateMapper<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(Func<IDataReader, object> deserializer, Func<IDataReader, object>[] otherDeserializers, object map) private static Func<IDataReader, TReturn> GenerateMapper<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(Func<IDataReader, object> deserializer, Func<IDataReader, object>[] otherDeserializers, object map)
{ {
switch(otherDeserializers.Length) switch (otherDeserializers.Length)
{ {
case 1: case 1:
return r => ((Func<TFirst, TSecond, TReturn>)map)((TFirst)deserializer(r), (TSecond)otherDeserializers[0](r)); return r => ((Func<TFirst, TSecond, TReturn>)map)((TFirst)deserializer(r), (TSecond)otherDeserializers[0](r));
...@@ -1148,7 +1147,7 @@ private static CacheInfo GetCacheInfo(Identity identity) ...@@ -1148,7 +1147,7 @@ private static CacheInfo GetCacheInfo(Identity identity)
{ {
if (typeof(IDynamicParameters).IsAssignableFrom(identity.parametersType)) if (typeof(IDynamicParameters).IsAssignableFrom(identity.parametersType))
{ {
info.ParamReader = (cmd, obj) => { (obj as IDynamicParameters).AddParameters(cmd,identity); }; info.ParamReader = (cmd, obj) => { (obj as IDynamicParameters).AddParameters(cmd, identity); };
} }
#if !CSHARP30 #if !CSHARP30
else if (typeof(IEnumerable<KeyValuePair<string, object>>).IsAssignableFrom(identity.parametersType) && typeof(System.Dynamic.IDynamicMetaObjectProvider).IsAssignableFrom(identity.parametersType)) else if (typeof(IEnumerable<KeyValuePair<string, object>>).IsAssignableFrom(identity.parametersType) && typeof(System.Dynamic.IDynamicMetaObjectProvider).IsAssignableFrom(identity.parametersType))
...@@ -1175,9 +1174,9 @@ private static CacheInfo GetCacheInfo(Identity identity) ...@@ -1175,9 +1174,9 @@ private static CacheInfo GetCacheInfo(Identity identity)
#if !CSHARP30 #if !CSHARP30
// dynamic is passed in as Object ... by c# design // dynamic is passed in as Object ... by c# design
if (type == typeof(object) if (type == typeof(object)
|| type == typeof(DapperRow)) || type == typeof(FastExpando))
{ {
return GetDapperRowDeserializer(reader, startBound, length, returnNullIfFirstMissing); return GetDynamicDeserializer(reader, startBound, length, returnNullIfFirstMissing);
} }
#else #else
if(type.IsAssignableFrom(typeof(Dictionary<string,object>))) if(type.IsAssignableFrom(typeof(Dictionary<string,object>)))
...@@ -1194,398 +1193,131 @@ private static CacheInfo GetCacheInfo(Identity identity) ...@@ -1194,398 +1193,131 @@ private static CacheInfo GetCacheInfo(Identity identity)
return GetStructDeserializer(type, underlyingType ?? type, startBound); return GetStructDeserializer(type, underlyingType ?? type, startBound);
} }
#if !CSHARP30 #if !CSHARP30
sealed partial class DapperTable private partial class FastExpando : System.Dynamic.DynamicObject, IDictionary<string, object>
{
const int CutOff = 10;
public readonly static DapperTable Empty = new DapperTable(null);
readonly Tuple<string, int>[] m_nameToIndex;
readonly Dictionary<string, int> m_nameToIndexLookup;
public DapperTable(IEnumerable<Tuple<string, int>> nameToIndex)
{
nameToIndex = nameToIndex ?? new Tuple<string, int>[0];
m_nameToIndex = nameToIndex.ToArray();
if (m_nameToIndex.Length < CutOff)
{
return;
}
m_nameToIndexLookup = new Dictionary<string, int>();
for (var index = 0; index < m_nameToIndex.Length; index++)
{
var nti = m_nameToIndex[index];
var key = nti.Item1 ?? "";
// Duplicates are ignored
if (!m_nameToIndexLookup.ContainsKey(key))
{
m_nameToIndexLookup[key] = nti.Item2;
}
}
}
internal Tuple<string, int>[] FieldNames
{
get
{
return m_nameToIndex;
}
}
internal int IndexOfName(string name)
{
name = name ?? "";
if (m_nameToIndexLookup == null)
{
for (var index = 0; index < m_nameToIndex.Length; index++)
{
var nti = m_nameToIndex[index];
if (nti.Item1.Equals(name, StringComparison.Ordinal))
{
return nti.Item2;
}
}
return -1;
}
int result;
return
m_nameToIndexLookup.TryGetValue(name, out result)
? result
: -1
;
}
}
sealed partial class DapperRowMetaObject : System.Dynamic.DynamicMetaObject
{
static MethodInfo GetMethod<T>(System.Linq.Expressions.Expression<Action<T>> expression)
{
return ((System.Linq.Expressions.MethodCallExpression) expression.Body).Method;
}
static readonly MethodInfo s_getValueMethod = GetMethod<DapperRow>(row => row.GetValue(default(string)));
static readonly MethodInfo s_setValueMethod = GetMethod<DapperRow>(row => row.SetValue(default(string), default(object)));
public DapperRowMetaObject(
System.Linq.Expressions.Expression expression,
System.Dynamic.BindingRestrictions restrictions
)
: base(expression, restrictions)
{
}
public DapperRowMetaObject(
System.Linq.Expressions.Expression expression,
System.Dynamic.BindingRestrictions restrictions,
object value
)
: base(expression, restrictions, value)
{
}
System.Dynamic.DynamicMetaObject CallMethod(
MethodInfo method,
System.Linq.Expressions.Expression[] parameters
)
{
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;
}
public override System.Dynamic.DynamicMetaObject BindGetMember(System.Dynamic.GetMemberBinder binder)
{ {
var parameters = new System.Linq.Expressions.Expression[] IDictionary<string, object> data;
{
System.Linq.Expressions.Expression.Constant(binder.Name)
};
var callMethod = CallMethod(s_getValueMethod, parameters);
return callMethod;
}
public override System.Dynamic.DynamicMetaObject BindSetMember(System.Dynamic.SetMemberBinder binder, System.Dynamic.DynamicMetaObject value) public static FastExpando Attach(IDictionary<string, object> data)
{ {
var parameters = new System.Linq.Expressions.Expression[] return new FastExpando { data = data };
{
System.Linq.Expressions.Expression.Constant(binder.Name) ,
value.Expression,
};
var callMethod = CallMethod(s_setValueMethod, parameters);
return callMethod;
}
} }
sealed partial class DapperRow public override bool TrySetMember(System.Dynamic.SetMemberBinder binder, object value)
: System.Dynamic.IDynamicMetaObjectProvider
, IDictionary<string, object>
{ {
static readonly object[] s_emptyValues = new object[0]; data[binder.Name] = value;
return true;
DapperTable m_table;
object[] m_values;
Dictionary<string, object> m_additionalValues;
public DapperRow(DapperTable table, object[] values)
{
m_table = table ?? DapperTable.Empty ;
m_values = values ?? s_emptyValues ;
} }
public DapperTable Table public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
{ {
get { return m_table; } return data.TryGetValue(binder.Name, out result);
} }
public int Count public override IEnumerable<string> GetDynamicMemberNames()
{ {
get { return Table.FieldNames.Length + (m_additionalValues != null ? m_additionalValues.Count : 0); } return data.Keys;
} }
public bool TryGetValue(string name, out object value) #region IDictionary<string,object> Members
{
value = null;
var index = Table.IndexOfName(name);
if (index == -1)
{
if (m_additionalValues == null)
{
return false;
}
return m_additionalValues.TryGetValue(name ?? "", out value);
}
value = GetFieldValueImpl(index);
return true;
}
public object GetValue(string name) void IDictionary<string, object>.Add(string key, object value)
{ {
object value; data.Add(key, value);
return TryGetValue(name, out value) ? value : null;
} }
public object SetValue(string name, object value) bool IDictionary<string, object>.ContainsKey(string key)
{
var index = Table.IndexOfName(name);
if (index == -1)
{
if (m_additionalValues == null)
{ {
m_additionalValues = new Dictionary<string, object>(); return data.ContainsKey(key);
}
m_additionalValues[name ?? ""] = value;
return value;
}
return SetFieldValueImpl(index, value);
} }
object GetFieldValueImpl(int i) ICollection<string> IDictionary<string, object>.Keys
{
var value = m_values[i];
if (value is DBNull)
{ {
return null; get { return data.Keys; }
} }
return value; bool IDictionary<string, object>.Remove(string key)
}
object SetFieldValueImpl(int i, object value)
{ {
m_values[i] = value; return data.Remove(key);
return value;
} }
public override string ToString() bool IDictionary<string, object>.TryGetValue(string key, out object value)
{
var sb = new StringBuilder("{DapperRow");
foreach (var kv in this)
{
var value = kv.Value;
sb.Append(", ");
sb.Append(kv.Key);
if (value != null)
{ {
sb.Append(" = '"); return data.TryGetValue(key, out value);
sb.Append(kv.Value);
sb.Append('\'');
}
else
{
sb.Append(" = NULL");
}
}
sb.Append('}');
return sb.ToString();
} }
public System.Dynamic.DynamicMetaObject GetMetaObject(System.Linq.Expressions.Expression parameter) ICollection<object> IDictionary<string, object>.Values
{ {
return new DapperRowMetaObject(parameter, System.Dynamic.BindingRestrictions.Empty, this); get { return data.Values; }
} }
public IEnumerator<KeyValuePair<string, object>> GetEnumerator() object IDictionary<string, object>.this[string key]
{ {
for (var index = 0; index < Table.FieldNames.Length; index++) get
{ {
var fieldName = Table.FieldNames[index]; return data[key];
yield return new KeyValuePair<string, object>(fieldName.Item1, GetFieldValueImpl(fieldName.Item2));
} }
set
if (m_additionalValues != null)
{ {
foreach (var additionalValue in m_additionalValues) data[key] = value;
{
yield return additionalValue;
}
} }
} }
IEnumerator IEnumerable.GetEnumerator() #endregion
{
return GetEnumerator();
}
#region Implementation of ICollection<KeyValuePair<string,object>> #region ICollection<KeyValuePair<string,object>> Members
void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item) void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item)
{ {
IDictionary<string, object> dic = this; data.Add(item);
dic.Add(item.Key, item.Value);
} }
void ICollection<KeyValuePair<string, object>>.Clear() void ICollection<KeyValuePair<string, object>>.Clear()
{ {
m_table = DapperTable.Empty ; data.Clear();
m_values = s_emptyValues ;
m_additionalValues = null ;
} }
bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item) bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item)
{ {
object value; return data.Contains(item);
return TryGetValue(item.Key, out value) && Equals(value, item.Value);
} }
void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex) void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{ {
foreach (var kv in this) data.CopyTo(array, arrayIndex);
{
if (arrayIndex < array.Length)
{
array[arrayIndex] = kv;
}
else
{
return;
}
++arrayIndex;
}
} }
bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item) int ICollection<KeyValuePair<string, object>>.Count
{ {
IDictionary<string, object> dic = this; get { return data.Count; }
return dic.Remove(item.Key);
} }
bool ICollection<KeyValuePair<string, object>>.IsReadOnly bool ICollection<KeyValuePair<string, object>>.IsReadOnly
{ {
get { return false; } get { return true; }
}
#endregion
#region Implementation of IDictionary<string,object>
bool IDictionary<string, object>.ContainsKey(string key)
{
object value;
return TryGetValue(key, out value);
}
void IDictionary<string, object>.Add(string key, object value)
{
IDictionary<string, object> dic = this;
if (dic.ContainsKey(key ?? ""))
{
throw new ArgumentException("An item with the same key has already been added." ,"key");
} }
SetValue(key, value); bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item)
}
bool IDictionary<string, object>.Remove(string key)
{
var name = key ?? "";
if (m_additionalValues != null && m_additionalValues.Remove(name))
{ {
return true; return data.Remove(item);
} }
var index = Table.IndexOfName(name); #endregion
if (index == -1)
{
return false;
}
if (m_additionalValues == null) #region IEnumerable<KeyValuePair<string,object>> Members
{
m_additionalValues = new Dictionary<string, object>();
}
for (var i = 0; i < Table.FieldNames.Length; i++) IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator()
{ {
var fieldName = Table.FieldNames[i]; return data.GetEnumerator();
m_additionalValues[fieldName.Item1] = GetFieldValueImpl(fieldName.Item2);
}
m_additionalValues.Remove(name);
m_table = DapperTable.Empty;
return true;
} }
object IDictionary<string, object>.this[string key] #endregion
{
get { return GetValue(key); }
set { SetValue(key, value); }
}
ICollection<string> IDictionary<string, object>.Keys #region IEnumerable Members
{
get { return this.Select(kv => kv.Key).ToArray(); }
}
ICollection<object> IDictionary<string, object>.Values IEnumerator IEnumerable.GetEnumerator()
{ {
get { return this.Select(kv => kv.Value).ToArray(); } return data.GetEnumerator();
} }
#endregion #endregion
...@@ -1593,62 +1325,11 @@ IEnumerator IEnumerable.GetEnumerator() ...@@ -1593,62 +1325,11 @@ IEnumerator IEnumerable.GetEnumerator()
#endif #endif
#if !CSHARP30 #if !CSHARP30
internal static Func<IDataReader, object> GetDapperRowDeserializer(IDataRecord reader, int startBound, int length, bool returnNullIfFirstMissing) private static Func<IDataReader, object> GetDynamicDeserializer(IDataRecord reader, int startBound, int length, bool returnNullIfFirstMissing)
{
var fieldCount = reader.FieldCount;
if (length == -1)
{
length = fieldCount - startBound;
}
if (fieldCount <= startBound)
{
throw new ArgumentException("When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id", "splitOn");
}
var effectiveFieldCount = fieldCount - startBound;
DapperTable table = null;
return
r =>
{
if(table == null)
{
table = new DapperTable(Enumerable
.Range(0, effectiveFieldCount)
.Select(i => Tuple.Create(reader.GetName(i + startBound), i)))
;
}
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);
}
else
{
var begin = returnNullIfFirstMissing ? 1 : 0;
for (var iter = begin; iter < effectiveFieldCount; ++iter)
{
values[iter] = r.GetValue(iter + startBound);
}
}
return new DapperRow(table, values);
};
}
#else #else
internal static Func<IDataReader, object> GetDictionaryDeserializer(IDataRecord reader, int startBound, int length, bool returnNullIfFirstMissing) private static Func<IDataReader, object> GetDictionaryDeserializer(IDataRecord reader, int startBound, int length, bool returnNullIfFirstMissing)
#endif
{ {
var fieldCount = reader.FieldCount; var fieldCount = reader.FieldCount;
if (length == -1) if (length == -1)
...@@ -1675,10 +1356,15 @@ IEnumerator IEnumerable.GetEnumerator() ...@@ -1675,10 +1356,15 @@ IEnumerator IEnumerable.GetEnumerator()
return null; return null;
} }
} }
#if !CSHARP30
//we know this is an object so it will not box
return FastExpando.Attach(row);
#else
return row; return row;
#endif
}; };
} }
#endif
/// <summary> /// <summary>
/// Internal use only /// Internal use only
/// </summary> /// </summary>
...@@ -1764,7 +1450,7 @@ public static void PackListParameters(IDbCommand command, string namePrefix, obj ...@@ -1764,7 +1450,7 @@ public static void PackListParameters(IDbCommand command, string namePrefix, obj
if (isString) if (isString)
{ {
listParam.Size = 4000; listParam.Size = 4000;
if (item != null && ((string) item).Length > 4000) if (item != null && ((string)item).Length > 4000)
{ {
listParam.Size = -1; listParam.Size = -1;
} }
...@@ -1885,7 +1571,7 @@ private static IEnumerable<PropertyInfo> FilterParameters(IEnumerable<PropertyIn ...@@ -1885,7 +1571,7 @@ private static IEnumerable<PropertyInfo> FilterParameters(IEnumerable<PropertyIn
il.Emit(OpCodes.Ldstr, prop.Name); // stack is now [parameters] [parameters] [parameter] [parameter] [name] 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] il.EmitCall(OpCodes.Callvirt, typeof(IDataParameter).GetProperty("ParameterName").GetSetMethod(), null);// stack is now [parameters] [parameters] [parameter]
} }
if(dbType != DbType.Time) // https://connect.microsoft.com/VisualStudio/feedback/details/381934/sqlparameter-dbtype-dbtype-time-sets-the-parameter-to-sqldbtype-datetime-instead-of-sqldbtype-time if (dbType != DbType.Time) // https://connect.microsoft.com/VisualStudio/feedback/details/381934/sqlparameter-dbtype-dbtype-time-sets-the-parameter-to-sqldbtype-datetime-instead-of-sqldbtype-time
{ {
il.Emit(OpCodes.Dup);// stack is now [parameters] [[parameters]] [parameter] [parameter] il.Emit(OpCodes.Dup);// stack is now [parameters] [[parameters]] [parameter] [parameter]
EmitInt32(il, (int)dbType);// stack is now [parameters] [[parameters]] [parameter] [parameter] [db-type] EmitInt32(il, (int)dbType);// stack is now [parameters] [[parameters]] [parameter] [parameter] [db-type]
...@@ -2071,13 +1757,13 @@ public static ITypeMap GetTypeMap(Type type) ...@@ -2071,13 +1757,13 @@ public static ITypeMap GetTypeMap(Type type)
{ {
if (type == null) throw new ArgumentNullException("type"); if (type == null) throw new ArgumentNullException("type");
var map = (ITypeMap)_typeMaps[type]; var map = (ITypeMap)_typeMaps[type];
if(map == null) if (map == null)
{ {
lock(_typeMaps) lock (_typeMaps)
{ // double-checked; store this to avoid reflection next time we see this type { // 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 // since multiple queries commonly use the same domain-entity/DTO/view-model type
map = (ITypeMap)_typeMaps[type]; map = (ITypeMap)_typeMaps[type];
if(map == null) if (map == null)
{ {
map = new DefaultTypeMap(type); map = new DefaultTypeMap(type);
_typeMaps[type] = map; _typeMaps[type] = map;
...@@ -2131,7 +1817,7 @@ public static void SetTypeMap(Type type, ITypeMap map) ...@@ -2131,7 +1817,7 @@ public static void SetTypeMap(Type type, ITypeMap map)
#if CSHARP30 #if CSHARP30
Type type, IDataReader reader, int startBound, int length, bool returnNullIfFirstMissing Type type, IDataReader reader, int startBound, int length, bool returnNullIfFirstMissing
#else #else
Type type, IDataReader reader, int startBound = 0, int length = -1, bool returnNullIfFirstMissing = false Type type, IDataReader reader, int startBound = 0, int length = -1, bool returnNullIfFirstMissing = false
#endif #endif
) )
{ {
...@@ -2199,11 +1885,11 @@ public static void SetTypeMap(Type type, ITypeMap map) ...@@ -2199,11 +1885,11 @@ public static void SetTypeMap(Type type, ITypeMap map)
} }
il.BeginExceptionBlock(); il.BeginExceptionBlock();
if(type.IsValueType) if (type.IsValueType)
{ {
il.Emit(OpCodes.Ldloca_S, (byte)1);// [target] il.Emit(OpCodes.Ldloca_S, (byte)1);// [target]
} }
else if(specializedConstructor == null) else if (specializedConstructor == null)
{ {
il.Emit(OpCodes.Ldloc_1);// [target] il.Emit(OpCodes.Ldloc_1);// [target]
} }
...@@ -2350,7 +2036,7 @@ public static void SetTypeMap(Type type, ITypeMap map) ...@@ -2350,7 +2036,7 @@ public static void SetTypeMap(Type type, ITypeMap map)
{ // use flexible conversion { // use flexible conversion
il.Emit(OpCodes.Ldtoken, unboxType); // stack is now [target][target][value][member-type-token] il.Emit(OpCodes.Ldtoken, unboxType); // stack is now [target][target][value][member-type-token]
il.EmitCall(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"), null); // stack is now [target][target][value][member-type] il.EmitCall(OpCodes.Call, typeof(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.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, unboxType); // stack is now [target][target][typed-value] il.Emit(OpCodes.Unbox_Any, unboxType); // stack is now [target][target][typed-value]
} }
...@@ -2435,19 +2121,19 @@ public static void SetTypeMap(Type type, ITypeMap map) ...@@ -2435,19 +2121,19 @@ public static void SetTypeMap(Type type, ITypeMap map)
il.EndExceptionBlock(); il.EndExceptionBlock();
il.Emit(OpCodes.Ldloc_1); // stack is [rval] il.Emit(OpCodes.Ldloc_1); // stack is [rval]
if(type.IsValueType) if (type.IsValueType)
{ {
il.Emit(OpCodes.Box, type); il.Emit(OpCodes.Box, type);
} }
il.Emit(OpCodes.Ret); il.Emit(OpCodes.Ret);
return (Func<IDataReader, object>)dm.CreateDelegate(typeof(Func<IDataReader,object>)); return (Func<IDataReader, object>)dm.CreateDelegate(typeof(Func<IDataReader, object>));
} }
private static void LoadLocal(ILGenerator il, int index) private static void LoadLocal(ILGenerator il, int index)
{ {
if(index < 0 || index >= short.MaxValue) throw new ArgumentNullException("index"); if (index < 0 || index >= short.MaxValue) throw new ArgumentNullException("index");
switch(index) switch (index)
{ {
case 0: il.Emit(OpCodes.Ldloc_0); break; case 0: il.Emit(OpCodes.Ldloc_0); break;
case 1: il.Emit(OpCodes.Ldloc_1); break; case 1: il.Emit(OpCodes.Ldloc_1); break;
...@@ -2525,7 +2211,8 @@ public static void ThrowDataException(Exception ex, int index, IDataReader reade ...@@ -2525,7 +2211,8 @@ public static void ThrowDataException(Exception ex, int index, IDataReader reade
} }
} }
toThrow = new DataException(string.Format("Error parsing column {0} ({1}={2})", index, name, value), ex); toThrow = new DataException(string.Format("Error parsing column {0} ({1}={2})", index, name, value), ex);
} catch }
catch
{ // throw the **original** exception, wrapped as DataException { // throw the **original** exception, wrapped as DataException
toThrow = new DataException(ex.Message, ex); toThrow = new DataException(ex.Message, ex);
} }
...@@ -2581,7 +2268,7 @@ internal GridReader(IDbCommand command, IDataReader reader, Identity identity) ...@@ -2581,7 +2268,7 @@ internal GridReader(IDbCommand command, IDataReader reader, Identity identity)
/// </summary> /// </summary>
public IEnumerable<dynamic> Read() public IEnumerable<dynamic> Read()
{ {
return Read<DapperRow>(); return Read<FastExpando>();
} }
#endif #endif
...@@ -2700,7 +2387,6 @@ public IEnumerable<T> Read<T>() ...@@ -2700,7 +2387,6 @@ public IEnumerable<T> Read<T>()
/// <param name="splitOn"></param> /// <param name="splitOn"></param>
/// <returns></returns> /// <returns></returns>
public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn> func, string splitOn = "id") public IEnumerable<TReturn> Read<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn> func, string splitOn = "id")
{ {
return MultiReadInternal<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(func, splitOn); return MultiReadInternal<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(func, splitOn);
} }
...@@ -2808,7 +2494,7 @@ public DynamicParameters(object template) ...@@ -2808,7 +2494,7 @@ public DynamicParameters(object template)
#if CSHARP30 #if CSHARP30
object param object param
#else #else
dynamic param dynamic param
#endif #endif
) )
{ {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment