DataStorage.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. //------------------------------------------------------------------------------
  2. // <copyright file="DataStorage.cs" company="Microsoft">
  3. // Copyright (c) Microsoft Corporation. All rights reserved.
  4. // </copyright>
  5. // <owner current="true" primary="true">Microsoft</owner>
  6. // <owner current="true" primary="false">Microsoft</owner>
  7. //------------------------------------------------------------------------------
  8. namespace System.Data.Common {
  9. using System;
  10. using System.Collections;
  11. using System.Collections.Concurrent;
  12. using System.Collections.Generic;
  13. using System.Data.SqlTypes;
  14. using System.Diagnostics;
  15. using System.Xml;
  16. using System.Xml.Serialization;
  17. internal enum StorageType {
  18. Empty = TypeCode.Empty, // 0
  19. Object = TypeCode.Object,
  20. DBNull = TypeCode.DBNull,
  21. Boolean = TypeCode.Boolean,
  22. Char = TypeCode.Char,
  23. SByte = TypeCode.SByte,
  24. Byte = TypeCode.Byte,
  25. Int16 = TypeCode.Int16,
  26. UInt16 = TypeCode.UInt16,
  27. Int32 = TypeCode.Int32,
  28. UInt32 = TypeCode.UInt32,
  29. Int64 = TypeCode.Int64,
  30. UInt64 = TypeCode.UInt64,
  31. Single = TypeCode.Single,
  32. Double = TypeCode.Double,
  33. Decimal = TypeCode.Decimal, // 15
  34. DateTime = TypeCode.DateTime, // 16
  35. TimeSpan = 17,
  36. String = TypeCode.String, // 18
  37. Guid = 19,
  38. ByteArray = 20,
  39. CharArray = 21,
  40. Type = 22,
  41. DateTimeOffset = 23,
  42. BigInteger = 24,
  43. Uri = 25,
  44. SqlBinary, // SqlTypes should remain at the end for IsSqlType checking
  45. SqlBoolean,
  46. SqlByte,
  47. SqlBytes,
  48. SqlChars,
  49. SqlDateTime,
  50. SqlDecimal,
  51. SqlDouble,
  52. SqlGuid,
  53. SqlInt16,
  54. SqlInt32,
  55. SqlInt64,
  56. SqlMoney,
  57. SqlSingle,
  58. SqlString,
  59. // SqlXml,
  60. };
  61. abstract internal class DataStorage {
  62. // for Whidbey 40426, searching down the Type[] is about 20% faster than using a Dictionary
  63. // must keep in same order as enum StorageType
  64. private static readonly Type[] StorageClassType = new Type[] {
  65. null,
  66. typeof(Object),
  67. typeof(DBNull),
  68. typeof(Boolean),
  69. typeof(Char),
  70. typeof(SByte),
  71. typeof(Byte),
  72. typeof(Int16),
  73. typeof(UInt16),
  74. typeof(Int32),
  75. typeof(UInt32),
  76. typeof(Int64),
  77. typeof(UInt64),
  78. typeof(Single),
  79. typeof(Double),
  80. typeof(Decimal),
  81. typeof(DateTime),
  82. typeof(TimeSpan),
  83. typeof(String),
  84. typeof(Guid),
  85. typeof(byte[]),
  86. typeof(char[]),
  87. typeof(Type),
  88. typeof(DateTimeOffset),
  89. typeof(System.Numerics.BigInteger),
  90. typeof(Uri),
  91. typeof(SqlBinary),
  92. typeof(SqlBoolean),
  93. typeof(SqlByte),
  94. typeof(SqlBytes),
  95. typeof(SqlChars),
  96. typeof(SqlDateTime),
  97. typeof(SqlDecimal),
  98. typeof(SqlDouble),
  99. typeof(SqlGuid),
  100. typeof(SqlInt16),
  101. typeof(SqlInt32),
  102. typeof(SqlInt64),
  103. typeof(SqlMoney),
  104. typeof(SqlSingle),
  105. typeof(SqlString),
  106. // typeof(SqlXml),
  107. };
  108. internal readonly DataColumn Column;
  109. internal readonly DataTable Table;
  110. internal readonly Type DataType;
  111. internal readonly StorageType StorageTypeCode;
  112. private System.Collections.BitArray dbNullBits;
  113. private readonly object DefaultValue;
  114. internal readonly object NullValue;
  115. internal readonly bool IsCloneable;
  116. internal readonly bool IsCustomDefinedType;
  117. internal readonly bool IsStringType;
  118. internal readonly bool IsValueType;
  119. private readonly static Func<Type, Tuple<bool, bool, bool, bool>> _inspectTypeForInterfaces = InspectTypeForInterfaces;
  120. private readonly static ConcurrentDictionary<Type, Tuple<bool, bool, bool, bool>> _typeImplementsInterface = new ConcurrentDictionary<Type, Tuple<bool, bool, bool, bool>>();
  121. protected DataStorage(DataColumn column, Type type, object defaultValue, StorageType storageType)
  122. : this(column, type, defaultValue, DBNull.Value, false, storageType) {
  123. }
  124. protected DataStorage(DataColumn column, Type type, object defaultValue, object nullValue, StorageType storageType)
  125. : this(column, type, defaultValue, nullValue, false, storageType) {
  126. }
  127. protected DataStorage(DataColumn column, Type type, object defaultValue, object nullValue, bool isICloneable, StorageType storageType) {
  128. Debug.Assert(storageType == GetStorageType(type), "Incorrect storage type specified");
  129. Column = column;
  130. Table = column.Table;
  131. DataType = type;
  132. StorageTypeCode = storageType;
  133. DefaultValue = defaultValue;
  134. NullValue = nullValue;
  135. IsCloneable = isICloneable;
  136. IsCustomDefinedType = IsTypeCustomType(StorageTypeCode);
  137. IsStringType = ((StorageType.String == StorageTypeCode) || (StorageType.SqlString == StorageTypeCode));
  138. IsValueType = DetermineIfValueType(StorageTypeCode, type);
  139. }
  140. internal DataSetDateTime DateTimeMode {
  141. get {
  142. return Column.DateTimeMode;
  143. }
  144. }
  145. internal IFormatProvider FormatProvider {
  146. get {
  147. return Table.FormatProvider;
  148. }
  149. }
  150. public virtual Object Aggregate(int[] recordNos, AggregateType kind) {
  151. if (AggregateType.Count == kind) {
  152. return this.AggregateCount(recordNos);
  153. }
  154. return null;
  155. }
  156. public object AggregateCount(int[] recordNos) {
  157. int count = 0;
  158. for (int i = 0; i < recordNos.Length; i++) {
  159. if (!this.dbNullBits.Get(recordNos[i]))
  160. count++;
  161. }
  162. return count;
  163. }
  164. protected int CompareBits(int recordNo1, int recordNo2) {
  165. bool recordNo1Null = this.dbNullBits.Get(recordNo1);
  166. bool recordNo2Null = this.dbNullBits.Get(recordNo2);
  167. if (recordNo1Null ^ recordNo2Null) {
  168. if (recordNo1Null)
  169. return -1;
  170. else
  171. return 1;
  172. }
  173. return 0;
  174. }
  175. public abstract int Compare(int recordNo1, int recordNo2);
  176. // only does comparision, expect value to be of the correct type
  177. public abstract int CompareValueTo(int recordNo1, object value);
  178. // only does conversion with support for reference null
  179. public virtual object ConvertValue(object value) {
  180. return value;
  181. }
  182. protected void CopyBits(int srcRecordNo, int dstRecordNo) {
  183. this.dbNullBits.Set(dstRecordNo, this.dbNullBits.Get(srcRecordNo));
  184. }
  185. abstract public void Copy(int recordNo1, int recordNo2);
  186. abstract public Object Get(int recordNo);
  187. protected Object GetBits(int recordNo) {
  188. if (this.dbNullBits.Get(recordNo)) {
  189. return NullValue;
  190. }
  191. return DefaultValue;
  192. }
  193. virtual public int GetStringLength(int record) {
  194. System.Diagnostics.Debug.Assert(false, "not a String or SqlString column");
  195. return Int32.MaxValue;
  196. }
  197. protected bool HasValue(int recordNo) {
  198. return !this.dbNullBits.Get(recordNo);
  199. }
  200. public virtual bool IsNull(int recordNo) {
  201. return this.dbNullBits.Get(recordNo);
  202. }
  203. // convert (may not support reference null) and store the value
  204. abstract public void Set(int recordNo, Object value);
  205. protected void SetNullBit(int recordNo, bool flag) {
  206. this.dbNullBits.Set(recordNo, flag);
  207. }
  208. virtual public void SetCapacity(int capacity) {
  209. if (null == this.dbNullBits) {
  210. this.dbNullBits = new BitArray(capacity);
  211. }
  212. else {
  213. this.dbNullBits.Length = capacity;
  214. }
  215. }
  216. abstract public object ConvertXmlToObject(string s);
  217. public virtual object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute xmlAttrib) {
  218. return ConvertXmlToObject(xmlReader.Value);
  219. }
  220. abstract public string ConvertObjectToXml(object value);
  221. public virtual void ConvertObjectToXml(object value, XmlWriter xmlWriter, XmlRootAttribute xmlAttrib) {
  222. xmlWriter.WriteString(ConvertObjectToXml(value));// should it be NO OP?
  223. }
  224. public static DataStorage CreateStorage(DataColumn column, Type dataType, StorageType typeCode) {
  225. Debug.Assert(typeCode == GetStorageType(dataType), "Incorrect storage type specified");
  226. if ((StorageType.Empty == typeCode) && (null != dataType)) {
  227. if (typeof(INullable).IsAssignableFrom(dataType)) { // Udt, OracleTypes
  228. return new SqlUdtStorage(column, dataType);
  229. }
  230. else {
  231. return new ObjectStorage(column, dataType); // non-nullable non-primitives
  232. }
  233. }
  234. switch (typeCode) {
  235. case StorageType.Empty: throw ExceptionBuilder.InvalidStorageType(TypeCode.Empty);
  236. case StorageType.DBNull: throw ExceptionBuilder.InvalidStorageType(TypeCode.DBNull);
  237. case StorageType.Object: return new ObjectStorage(column, dataType);
  238. case StorageType.Boolean: return new BooleanStorage(column);
  239. case StorageType.Char: return new CharStorage(column);
  240. case StorageType.SByte: return new SByteStorage(column);
  241. case StorageType.Byte: return new ByteStorage(column);
  242. case StorageType.Int16: return new Int16Storage(column);
  243. case StorageType.UInt16: return new UInt16Storage(column);
  244. case StorageType.Int32: return new Int32Storage(column);
  245. case StorageType.UInt32: return new UInt32Storage(column);
  246. case StorageType.Int64: return new Int64Storage(column);
  247. case StorageType.UInt64: return new UInt64Storage(column);
  248. case StorageType.Single: return new SingleStorage(column);
  249. case StorageType.Double: return new DoubleStorage(column);
  250. case StorageType.Decimal: return new DecimalStorage(column);
  251. case StorageType.DateTime: return new DateTimeStorage(column);
  252. case StorageType.TimeSpan: return new TimeSpanStorage(column);
  253. case StorageType.String: return new StringStorage(column);
  254. case StorageType.Guid: return new ObjectStorage(column, dataType);
  255. case StorageType.ByteArray: return new ObjectStorage(column, dataType);
  256. case StorageType.CharArray: return new ObjectStorage(column, dataType);
  257. case StorageType.Type: return new ObjectStorage(column, dataType);
  258. case StorageType.DateTimeOffset: return new DateTimeOffsetStorage(column);
  259. case StorageType.BigInteger: return new BigIntegerStorage(column);
  260. case StorageType.Uri: return new ObjectStorage(column, dataType);
  261. case StorageType.SqlBinary: return new SqlBinaryStorage(column);
  262. case StorageType.SqlBoolean: return new SqlBooleanStorage(column);
  263. case StorageType.SqlByte: return new SqlByteStorage(column);
  264. case StorageType.SqlBytes: return new SqlBytesStorage(column);
  265. case StorageType.SqlChars: return new SqlCharsStorage(column);
  266. case StorageType.SqlDateTime: return new SqlDateTimeStorage(column); //???/ what to do
  267. case StorageType.SqlDecimal: return new SqlDecimalStorage(column);
  268. case StorageType.SqlDouble: return new SqlDoubleStorage(column);
  269. case StorageType.SqlGuid: return new SqlGuidStorage(column);
  270. case StorageType.SqlInt16: return new SqlInt16Storage(column);
  271. case StorageType.SqlInt32: return new SqlInt32Storage(column);
  272. case StorageType.SqlInt64: return new SqlInt64Storage(column);
  273. case StorageType.SqlMoney: return new SqlMoneyStorage(column);
  274. case StorageType.SqlSingle: return new SqlSingleStorage(column);
  275. case StorageType.SqlString: return new SqlStringStorage(column);
  276. // case StorageType.SqlXml: return new SqlXmlStorage(column);
  277. default:
  278. System.Diagnostics.Debug.Assert(false, "shouldn't be here");
  279. goto case StorageType.Object;
  280. }
  281. }
  282. internal static StorageType GetStorageType(Type dataType) {
  283. for (int i = 0; i < StorageClassType.Length; ++i) {
  284. if (dataType == StorageClassType[i]) {
  285. return (StorageType)i;
  286. }
  287. }
  288. TypeCode tcode = Type.GetTypeCode(dataType);
  289. if (TypeCode.Object != tcode) { // enum -> Int64/Int32/Int16/Byte
  290. return (StorageType)tcode;
  291. }
  292. return StorageType.Empty;
  293. }
  294. internal static Type GetTypeStorage(StorageType storageType) {
  295. return StorageClassType[(int)storageType];
  296. }
  297. internal static bool IsTypeCustomType(Type type) {
  298. return IsTypeCustomType(GetStorageType(type));
  299. }
  300. internal static bool IsTypeCustomType(StorageType typeCode) {
  301. return ((StorageType.Object == typeCode) || (StorageType.Empty == typeCode) || (StorageType.CharArray == typeCode));
  302. }
  303. internal static bool IsSqlType(StorageType storageType) {
  304. return (StorageType.SqlBinary <= storageType);
  305. }
  306. public static bool IsSqlType(Type dataType) {
  307. for (int i = (int)StorageType.SqlBinary; i < StorageClassType.Length; ++i) {
  308. if (dataType == StorageClassType[i]) {
  309. return true;
  310. }
  311. }
  312. return false;
  313. }
  314. private static bool DetermineIfValueType(StorageType typeCode, Type dataType) {
  315. bool result;
  316. switch (typeCode) {
  317. case StorageType.Boolean:
  318. case StorageType.Char:
  319. case StorageType.SByte:
  320. case StorageType.Byte:
  321. case StorageType.Int16:
  322. case StorageType.UInt16:
  323. case StorageType.Int32:
  324. case StorageType.UInt32:
  325. case StorageType.Int64:
  326. case StorageType.UInt64:
  327. case StorageType.Single:
  328. case StorageType.Double:
  329. case StorageType.Decimal:
  330. case StorageType.DateTime:
  331. case StorageType.DateTimeOffset:
  332. case StorageType.BigInteger:
  333. case StorageType.TimeSpan:
  334. case StorageType.Guid:
  335. case StorageType.SqlBinary:
  336. case StorageType.SqlBoolean:
  337. case StorageType.SqlByte:
  338. case StorageType.SqlDateTime:
  339. case StorageType.SqlDecimal:
  340. case StorageType.SqlDouble:
  341. case StorageType.SqlGuid:
  342. case StorageType.SqlInt16:
  343. case StorageType.SqlInt32:
  344. case StorageType.SqlInt64:
  345. case StorageType.SqlMoney:
  346. case StorageType.SqlSingle:
  347. case StorageType.SqlString:
  348. result = true;
  349. break;
  350. case StorageType.String:
  351. case StorageType.ByteArray:
  352. case StorageType.CharArray:
  353. case StorageType.Type:
  354. case StorageType.Uri:
  355. case StorageType.SqlBytes:
  356. case StorageType.SqlChars:
  357. result = false;
  358. break;
  359. default:
  360. result = dataType.IsValueType;
  361. break;
  362. }
  363. Debug.Assert(result == dataType.IsValueType, "typeCode mismatches dataType");
  364. return result;
  365. }
  366. internal static void ImplementsInterfaces(
  367. StorageType typeCode,
  368. Type dataType,
  369. out bool sqlType,
  370. out bool nullable,
  371. out bool xmlSerializable,
  372. out bool changeTracking,
  373. out bool revertibleChangeTracking)
  374. {
  375. Debug.Assert(typeCode == GetStorageType(dataType), "typeCode mismatches dataType");
  376. if (IsSqlType(typeCode)) {
  377. sqlType = true;
  378. nullable = true;
  379. changeTracking = false;
  380. revertibleChangeTracking = false;
  381. xmlSerializable = true;
  382. }
  383. else if (StorageType.Empty != typeCode) {
  384. sqlType = false;
  385. nullable = false;
  386. changeTracking = false;
  387. revertibleChangeTracking = false;
  388. xmlSerializable = false;
  389. }
  390. else {
  391. // Non-standard type - look it up in the dictionary or add it if not found
  392. Tuple<bool, bool, bool, bool> interfaces = _typeImplementsInterface.GetOrAdd(dataType, _inspectTypeForInterfaces);
  393. sqlType = false;
  394. nullable = interfaces.Item1;
  395. changeTracking = interfaces.Item2;
  396. revertibleChangeTracking = interfaces.Item3;
  397. xmlSerializable = interfaces.Item4;
  398. }
  399. Debug.Assert(nullable == typeof(System.Data.SqlTypes.INullable).IsAssignableFrom(dataType), "INullable");
  400. Debug.Assert(changeTracking == typeof(System.ComponentModel.IChangeTracking).IsAssignableFrom(dataType), "IChangeTracking");
  401. Debug.Assert(revertibleChangeTracking == typeof(System.ComponentModel.IRevertibleChangeTracking).IsAssignableFrom(dataType), "IRevertibleChangeTracking");
  402. Debug.Assert(xmlSerializable == typeof(System.Xml.Serialization.IXmlSerializable).IsAssignableFrom(dataType), "IXmlSerializable");
  403. }
  404. private static Tuple<bool, bool, bool, bool> InspectTypeForInterfaces(Type dataType) {
  405. Debug.Assert(dataType != null, "Type should not be null");
  406. return new Tuple<bool,bool,bool,bool>(
  407. typeof(System.Data.SqlTypes.INullable).IsAssignableFrom(dataType),
  408. typeof(System.ComponentModel.IChangeTracking).IsAssignableFrom(dataType),
  409. typeof(System.ComponentModel.IRevertibleChangeTracking).IsAssignableFrom(dataType),
  410. typeof(System.Xml.Serialization.IXmlSerializable).IsAssignableFrom(dataType));
  411. }
  412. internal static bool ImplementsINullableValue(StorageType typeCode, Type dataType) {
  413. Debug.Assert(typeCode == GetStorageType(dataType), "typeCode mismatches dataType");
  414. return ((StorageType.Empty == typeCode) && dataType.IsGenericType && (dataType.GetGenericTypeDefinition() == typeof(System.Nullable<>)));
  415. }
  416. public static bool IsObjectNull(object value) {
  417. return ((null == value) || (DBNull.Value == value) || IsObjectSqlNull(value));
  418. }
  419. public static bool IsObjectSqlNull(object value) {
  420. INullable inullable = (value as INullable);
  421. return ((null != inullable) && inullable.IsNull);
  422. }
  423. internal object GetEmptyStorageInternal(int recordCount) {
  424. return GetEmptyStorage(recordCount);
  425. }
  426. internal void CopyValueInternal(int record, object store, BitArray nullbits, int storeIndex) {
  427. CopyValue(record, store, nullbits, storeIndex);
  428. }
  429. internal void SetStorageInternal(object store, BitArray nullbits) {
  430. SetStorage(store, nullbits);
  431. }
  432. abstract protected Object GetEmptyStorage(int recordCount);
  433. abstract protected void CopyValue(int record, object store, BitArray nullbits, int storeIndex);
  434. abstract protected void SetStorage(object store, BitArray nullbits);
  435. protected void SetNullStorage(BitArray nullbits) {
  436. dbNullBits = nullbits;
  437. }
  438. /// <summary>wrapper around Type.GetType</summary>
  439. /// <param name="value">assembly qualified type name or one of the special known types</param>
  440. /// <returns>Type or null if not found</returns>
  441. /// <exception cref="InvalidOperationException">when type implements IDynamicMetaObjectProvider and not IXmlSerializable</exception>
  442. /// <remarks>
  443. /// Types like "System.Guid" will load regardless of AssemblyQualifiedName because they are special
  444. /// Types like "System.Data.SqlTypes.SqlString" will load because they are in the same assembly as this code
  445. /// Types like "System.Numerics.BigInteger" won't load because they are not special and not same assembly as this code
  446. /// </remarks>
  447. internal static Type GetType(string value) {
  448. Type dataType = Type.GetType(value); // throwOnError=false, ignoreCase=fase
  449. if (null == dataType) {
  450. if ("System.Numerics.BigInteger" == value) {
  451. dataType = typeof(System.Numerics.BigInteger);
  452. }
  453. }
  454. // Dev10 671061: prevent reading type from schema which implements IDynamicMetaObjectProvider and not IXmlSerializable
  455. // the check here prevents the type from being loaded in schema or as instance data (when DataType is object)
  456. ObjectStorage.VerifyIDynamicMetaObjectProvider(dataType);
  457. return dataType;
  458. }
  459. /// <summary>wrapper around Type.AssemblyQualifiedName</summary>
  460. /// <param name="type"></param>
  461. /// <returns>qualified name when writing in xml</returns>
  462. /// <exception cref="InvalidOperationException">when type implements IDynamicMetaObjectProvider and not IXmlSerializable</exception>
  463. internal static string GetQualifiedName(Type type)
  464. {
  465. Debug.Assert(null != type, "null type");
  466. ObjectStorage.VerifyIDynamicMetaObjectProvider(type);
  467. return type.AssemblyQualifiedName;
  468. }
  469. }
  470. }