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 @@
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).
*/
using System;
using System.Collections;
using System.Collections.Generic;
......@@ -19,7 +18,6 @@
using System.Text.RegularExpressions;
using System.Diagnostics;
namespace Dapper
{
/// <summary>
......@@ -259,7 +257,7 @@ public static void PurgeQueryCache()
static readonly System.Collections.Concurrent.ConcurrentDictionary<Identity, CacheInfo> _queryCache = new System.Collections.Concurrent.ConcurrentDictionary<Identity, CacheInfo>();
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();
}
......@@ -290,7 +288,7 @@ private static void CollectCacheGarbage()
private static int collect;
private static bool TryGetQueryCache(Identity key, out CacheInfo value)
{
if(_queryCache.TryGetValue(key, out value))
if (_queryCache.TryGetValue(key, out value))
{
value.RecordHit();
return true;
......@@ -343,16 +341,17 @@ public static int GetCachedSQLCount()
/// Deep diagnostics only: find any hash collisions in the cache
/// </summary>
/// <returns></returns>
public static IEnumerable<Tuple<int,int>> GetHashCollissions()
public static IEnumerable<Tuple<int, int>> GetHashCollissions()
{
var counts = new Dictionary<int, int>();
foreach(var key in _queryCache.Keys)
foreach (var key in _queryCache.Keys)
{
int count;
if(!counts.TryGetValue(key.hashCode, out count))
if (!counts.TryGetValue(key.hashCode, out count))
{
counts.Add(key.hashCode, 1);
} else
}
else
{
counts[key.hashCode] = count + 1;
}
......@@ -703,7 +702,7 @@ public static GridReader QueryMultiple(this IDbConnection cnn, string sql, objec
// nice and simple
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);
}
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
/// </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)
{
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
/// <summary>
......@@ -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)
{
switch(otherDeserializers.Length)
switch (otherDeserializers.Length)
{
case 1:
return r => ((Func<TFirst, TSecond, TReturn>)map)((TFirst)deserializer(r), (TSecond)otherDeserializers[0](r));
......@@ -1148,7 +1147,7 @@ private static CacheInfo GetCacheInfo(Identity identity)
{
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
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)
#if !CSHARP30
// dynamic is passed in as Object ... by c# design
if (type == typeof(object)
|| type == typeof(DapperRow))
|| type == typeof(FastExpando))
{
return GetDapperRowDeserializer(reader, startBound, length, returnNullIfFirstMissing);
return GetDynamicDeserializer(reader, startBound, length, returnNullIfFirstMissing);
}
#else
if(type.IsAssignableFrom(typeof(Dictionary<string,object>)))
......@@ -1194,398 +1193,131 @@ private static CacheInfo GetCacheInfo(Identity identity)
return GetStructDeserializer(type, underlyingType ?? type, startBound);
}
#if !CSHARP30
sealed partial class DapperTable
{
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)
private partial class FastExpando : System.Dynamic.DynamicObject, IDictionary<string, object>
{
var parameters = new System.Linq.Expressions.Expression[]
{
System.Linq.Expressions.Expression.Constant(binder.Name)
};
var callMethod = CallMethod(s_getValueMethod, parameters);
return callMethod;
}
IDictionary<string, object> data;
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[]
{
System.Linq.Expressions.Expression.Constant(binder.Name) ,
value.Expression,
};
var callMethod = CallMethod(s_setValueMethod, parameters);
return callMethod;
}
return new FastExpando { data = data };
}
sealed partial class DapperRow
: System.Dynamic.IDynamicMetaObjectProvider
, IDictionary<string, object>
public override bool TrySetMember(System.Dynamic.SetMemberBinder binder, object value)
{
static readonly object[] s_emptyValues = new object[0];
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 ;
data[binder.Name] = value;
return true;
}
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)
{
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;
}
#region IDictionary<string,object> Members
public object GetValue(string name)
void IDictionary<string, object>.Add(string key, object value)
{
object value;
return TryGetValue(name, out value) ? value : null;
data.Add(key, value);
}
public object SetValue(string name, object value)
{
var index = Table.IndexOfName(name);
if (index == -1)
{
if (m_additionalValues == null)
bool IDictionary<string, object>.ContainsKey(string key)
{
m_additionalValues = new Dictionary<string, object>();
}
m_additionalValues[name ?? ""] = value;
return value;
}
return SetFieldValueImpl(index, value);
return data.ContainsKey(key);
}
object GetFieldValueImpl(int i)
{
var value = m_values[i];
if (value is DBNull)
ICollection<string> IDictionary<string, object>.Keys
{
return null;
get { return data.Keys; }
}
return value;
}
object SetFieldValueImpl(int i, object value)
bool IDictionary<string, object>.Remove(string key)
{
m_values[i] = value;
return value;
return data.Remove(key);
}
public override string ToString()
{
var sb = new StringBuilder("{DapperRow");
foreach (var kv in this)
{
var value = kv.Value;
sb.Append(", ");
sb.Append(kv.Key);
if (value != null)
bool IDictionary<string, object>.TryGetValue(string key, out object value)
{
sb.Append(" = '");
sb.Append(kv.Value);
sb.Append('\'');
}
else
{
sb.Append(" = NULL");
}
}
sb.Append('}');
return sb.ToString();
return data.TryGetValue(key, out value);
}
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];
yield return new KeyValuePair<string, object>(fieldName.Item1, GetFieldValueImpl(fieldName.Item2));
return data[key];
}
if (m_additionalValues != null)
set
{
foreach (var additionalValue in m_additionalValues)
{
yield return additionalValue;
}
data[key] = value;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region Implementation of ICollection<KeyValuePair<string,object>>
#region ICollection<KeyValuePair<string,object>> Members
void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item)
{
IDictionary<string, object> dic = this;
dic.Add(item.Key, item.Value);
data.Add(item);
}
void ICollection<KeyValuePair<string, object>>.Clear()
{
m_table = DapperTable.Empty ;
m_values = s_emptyValues ;
m_additionalValues = null ;
data.Clear();
}
bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item)
{
object value;
return TryGetValue(item.Key, out value) && Equals(value, item.Value);
return data.Contains(item);
}
void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{
foreach (var kv in this)
{
if (arrayIndex < array.Length)
{
array[arrayIndex] = kv;
}
else
{
return;
}
++arrayIndex;
}
data.CopyTo(array, arrayIndex);
}
bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item)
int ICollection<KeyValuePair<string, object>>.Count
{
IDictionary<string, object> dic = this;
return dic.Remove(item.Key);
get { return data.Count; }
}
bool ICollection<KeyValuePair<string, object>>.IsReadOnly
{
get { return false; }
}
#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");
get { return true; }
}
SetValue(key, value);
}
bool IDictionary<string, object>.Remove(string key)
{
var name = key ?? "";
if (m_additionalValues != null && m_additionalValues.Remove(name))
bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item)
{
return true;
return data.Remove(item);
}
var index = Table.IndexOfName(name);
if (index == -1)
{
return false;
}
#endregion
if (m_additionalValues == null)
{
m_additionalValues = new Dictionary<string, object>();
}
#region IEnumerable<KeyValuePair<string,object>> Members
for (var i = 0; i < Table.FieldNames.Length; i++)
IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator()
{
var fieldName = Table.FieldNames[i];
m_additionalValues[fieldName.Item1] = GetFieldValueImpl(fieldName.Item2);
}
m_additionalValues.Remove(name);
m_table = DapperTable.Empty;
return true;
return data.GetEnumerator();
}
object IDictionary<string, object>.this[string key]
{
get { return GetValue(key); }
set { SetValue(key, value); }
}
#endregion
ICollection<string> IDictionary<string, object>.Keys
{
get { return this.Select(kv => kv.Key).ToArray(); }
}
#region IEnumerable Members
ICollection<object> IDictionary<string, object>.Values
IEnumerator IEnumerable.GetEnumerator()
{
get { return this.Select(kv => kv.Value).ToArray(); }
return data.GetEnumerator();
}
#endregion
......@@ -1593,62 +1325,11 @@ IEnumerator IEnumerable.GetEnumerator()
#endif
#if !CSHARP30
internal static Func<IDataReader, object> GetDapperRowDeserializer(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);
};
}
private static Func<IDataReader, object> GetDynamicDeserializer(IDataRecord reader, int startBound, int length, bool returnNullIfFirstMissing)
#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;
if (length == -1)
......@@ -1675,10 +1356,15 @@ IEnumerator IEnumerable.GetEnumerator()
return null;
}
}
#if !CSHARP30
//we know this is an object so it will not box
return FastExpando.Attach(row);
#else
return row;
#endif
};
}
#endif
/// <summary>
/// Internal use only
/// </summary>
......@@ -1764,7 +1450,7 @@ public static void PackListParameters(IDbCommand command, string namePrefix, obj
if (isString)
{
listParam.Size = 4000;
if (item != null && ((string) item).Length > 4000)
if (item != null && ((string)item).Length > 4000)
{
listParam.Size = -1;
}
......@@ -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.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]
EmitInt32(il, (int)dbType);// stack is now [parameters] [[parameters]] [parameter] [parameter] [db-type]
......@@ -2071,13 +1757,13 @@ public static ITypeMap GetTypeMap(Type type)
{
if (type == null) throw new ArgumentNullException("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
// since multiple queries commonly use the same domain-entity/DTO/view-model type
map = (ITypeMap)_typeMaps[type];
if(map == null)
if (map == null)
{
map = new DefaultTypeMap(type);
_typeMaps[type] = map;
......@@ -2131,7 +1817,7 @@ public static void SetTypeMap(Type type, ITypeMap map)
#if CSHARP30
Type type, IDataReader reader, int startBound, int length, bool returnNullIfFirstMissing
#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
)
{
......@@ -2199,11 +1885,11 @@ public static void SetTypeMap(Type type, ITypeMap map)
}
il.BeginExceptionBlock();
if(type.IsValueType)
if (type.IsValueType)
{
il.Emit(OpCodes.Ldloca_S, (byte)1);// [target]
}
else if(specializedConstructor == null)
else if (specializedConstructor == null)
{
il.Emit(OpCodes.Ldloc_1);// [target]
}
......@@ -2350,7 +2036,7 @@ public static void SetTypeMap(Type type, ITypeMap map)
{ // use flexible conversion
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(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]
}
......@@ -2435,19 +2121,19 @@ public static void SetTypeMap(Type type, ITypeMap map)
il.EndExceptionBlock();
il.Emit(OpCodes.Ldloc_1); // stack is [rval]
if(type.IsValueType)
if (type.IsValueType)
{
il.Emit(OpCodes.Box, type);
}
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)
{
if(index < 0 || index >= short.MaxValue) throw new ArgumentNullException("index");
switch(index)
if (index < 0 || index >= short.MaxValue) throw new ArgumentNullException("index");
switch (index)
{
case 0: il.Emit(OpCodes.Ldloc_0); break;
case 1: il.Emit(OpCodes.Ldloc_1); break;
......@@ -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);
} catch
}
catch
{ // throw the **original** exception, wrapped as DataException
toThrow = new DataException(ex.Message, ex);
}
......@@ -2581,7 +2268,7 @@ internal GridReader(IDbCommand command, IDataReader reader, Identity identity)
/// </summary>
public IEnumerable<dynamic> Read()
{
return Read<DapperRow>();
return Read<FastExpando>();
}
#endif
......@@ -2700,7 +2387,6 @@ public IEnumerable<T> Read<T>()
/// <param name="splitOn"></param>
/// <returns></returns>
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);
}
......@@ -2808,7 +2494,7 @@ public DynamicParameters(object template)
#if CSHARP30
object param
#else
dynamic param
dynamic param
#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