SqlSequentialTextReader.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. using System;
  2. using System.Data.Common;
  3. using System.Diagnostics;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Data.SqlClient
  8. {
  9. sealed internal class SqlSequentialTextReader : System.IO.TextReader
  10. {
  11. private SqlDataReader _reader; // The SqlDataReader that we are reading data from
  12. private int _columnIndex; // The index of out column in the table
  13. private Encoding _encoding; // Encoding for this character stream
  14. private Decoder _decoder; // Decoder based on the encoding (NOTE: Decoders are stateful as they are designed to process streams of data)
  15. private byte[] _leftOverBytes; // Bytes leftover from the last Read() operation - this can be null if there were no bytes leftover (Possible optimization: re-use the same array?)
  16. private int _peekedChar; // The last character that we peeked at (or -1 if we haven't peeked at anything)
  17. private Task _currentTask; // The current async task
  18. private CancellationTokenSource _disposalTokenSource; // Used to indicate that a cancellation is requested due to disposal
  19. internal SqlSequentialTextReader(SqlDataReader reader, int columnIndex, Encoding encoding)
  20. {
  21. Debug.Assert(reader != null, "Null reader when creating sequential textreader");
  22. Debug.Assert(columnIndex >= 0, "Invalid column index when creating sequential textreader");
  23. Debug.Assert(encoding != null, "Null encoding when creating sequential textreader");
  24. _reader = reader;
  25. _columnIndex = columnIndex;
  26. _encoding = encoding;
  27. _decoder = encoding.GetDecoder();
  28. _leftOverBytes = null;
  29. _peekedChar = -1;
  30. _currentTask = null;
  31. _disposalTokenSource = new CancellationTokenSource();
  32. }
  33. internal int ColumnIndex
  34. {
  35. get { return _columnIndex; }
  36. }
  37. public override int Peek()
  38. {
  39. if (_currentTask != null)
  40. {
  41. throw ADP.AsyncOperationPending();
  42. }
  43. if (IsClosed)
  44. {
  45. throw ADP.ObjectDisposed(this);
  46. }
  47. if (!HasPeekedChar)
  48. {
  49. _peekedChar = Read();
  50. }
  51. Debug.Assert(_peekedChar == -1 || ((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue)), string.Format("Bad peeked character: {0}", _peekedChar));
  52. return _peekedChar;
  53. }
  54. public override int Read()
  55. {
  56. if (_currentTask != null)
  57. {
  58. throw ADP.AsyncOperationPending();
  59. }
  60. if (IsClosed)
  61. {
  62. throw ADP.ObjectDisposed(this);
  63. }
  64. int readChar = -1;
  65. // If there is already a peeked char, then return it
  66. if (HasPeekedChar)
  67. {
  68. readChar = _peekedChar;
  69. _peekedChar = -1;
  70. }
  71. // If there is data available try to read a char
  72. else
  73. {
  74. char[] tempBuffer = new char[1];
  75. int charsRead = InternalRead(tempBuffer, 0, 1);
  76. if (charsRead == 1)
  77. {
  78. readChar = tempBuffer[0];
  79. }
  80. }
  81. Debug.Assert(readChar == -1 || ((readChar >= char.MinValue) && (readChar <= char.MaxValue)), string.Format("Bad read character: {0}", readChar));
  82. return readChar;
  83. }
  84. public override int Read(char[] buffer, int index, int count)
  85. {
  86. ValidateReadParameters(buffer, index, count);
  87. if (IsClosed)
  88. {
  89. throw ADP.ObjectDisposed(this);
  90. }
  91. if (_currentTask != null)
  92. {
  93. throw ADP.AsyncOperationPending();
  94. }
  95. int charsRead = 0;
  96. int charsNeeded = count;
  97. // Load in peeked char
  98. if ((charsNeeded > 0) && (HasPeekedChar))
  99. {
  100. Debug.Assert((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue), string.Format("Bad peeked character: {0}", _peekedChar));
  101. buffer[index + charsRead] = (char)_peekedChar;
  102. charsRead++;
  103. charsNeeded--;
  104. _peekedChar = -1;
  105. }
  106. // If we need more data and there is data avaiable, read
  107. charsRead += InternalRead(buffer, index + charsRead, charsNeeded);
  108. return charsRead;
  109. }
  110. public override Task<int> ReadAsync(char[] buffer, int index, int count)
  111. {
  112. ValidateReadParameters(buffer, index, count);
  113. TaskCompletionSource<int> completion = new TaskCompletionSource<int>();
  114. if (IsClosed)
  115. {
  116. completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
  117. }
  118. else
  119. {
  120. try
  121. {
  122. Task original = Interlocked.CompareExchange<Task>(ref _currentTask, completion.Task, null);
  123. if (original != null)
  124. {
  125. completion.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
  126. }
  127. else
  128. {
  129. bool completedSynchronously = true;
  130. int charsRead = 0;
  131. int adjustedIndex = index;
  132. int charsNeeded = count;
  133. // Load in peeked char
  134. if ((HasPeekedChar) && (charsNeeded > 0))
  135. {
  136. // Take a copy of _peekedChar in case it is cleared during close
  137. int peekedChar = _peekedChar;
  138. if (peekedChar >= char.MinValue)
  139. {
  140. Debug.Assert((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue), string.Format("Bad peeked character: {0}", _peekedChar));
  141. buffer[adjustedIndex] = (char)peekedChar;
  142. adjustedIndex++;
  143. charsRead++;
  144. charsNeeded--;
  145. _peekedChar = -1;
  146. }
  147. }
  148. int byteBufferUsed;
  149. byte[] byteBuffer = PrepareByteBuffer(charsNeeded, out byteBufferUsed);
  150. // Permit a 0 byte read in order to advance the reader to the correct column
  151. if ((byteBufferUsed < byteBuffer.Length) || (byteBuffer.Length == 0))
  152. {
  153. int bytesRead;
  154. var reader = _reader;
  155. if (reader != null)
  156. {
  157. Task<int> getBytesTask = reader.GetBytesAsync(_columnIndex, byteBuffer, byteBufferUsed, byteBuffer.Length - byteBufferUsed, Timeout.Infinite, _disposalTokenSource.Token, out bytesRead);
  158. if (getBytesTask == null) {
  159. byteBufferUsed += bytesRead;
  160. }
  161. else {
  162. // We need more data - setup the callback, and mark this as not completed [....]
  163. completedSynchronously = false;
  164. getBytesTask.ContinueWith((t) =>
  165. {
  166. _currentTask = null;
  167. // If we completed but the textreader is closed, then report cancellation
  168. if ((t.Status == TaskStatus.RanToCompletion) && (!IsClosed))
  169. {
  170. try
  171. {
  172. int bytesReadFromStream = t.Result;
  173. byteBufferUsed += bytesReadFromStream;
  174. if (byteBufferUsed > 0)
  175. {
  176. charsRead += DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, adjustedIndex, charsNeeded);
  177. }
  178. completion.SetResult(charsRead);
  179. }
  180. catch (Exception ex)
  181. {
  182. completion.SetException(ex);
  183. }
  184. }
  185. else if (IsClosed)
  186. {
  187. completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
  188. }
  189. else if (t.Status == TaskStatus.Faulted)
  190. {
  191. if (t.Exception.InnerException is SqlException)
  192. {
  193. // ReadAsync can't throw a SqlException, so wrap it in an IOException
  194. completion.SetException(ADP.ExceptionWithStackTrace(ADP.ErrorReadingFromStream(t.Exception.InnerException)));
  195. }
  196. else
  197. {
  198. completion.SetException(t.Exception.InnerException);
  199. }
  200. }
  201. else
  202. {
  203. completion.SetCanceled();
  204. }
  205. }, TaskScheduler.Default);
  206. }
  207. if ((completedSynchronously) && (byteBufferUsed > 0))
  208. {
  209. // No more data needed, decode what we have
  210. charsRead += DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, adjustedIndex, charsNeeded);
  211. }
  212. }
  213. else
  214. {
  215. // Reader is null, close must of happened in the middle of this read
  216. completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
  217. }
  218. }
  219. if (completedSynchronously)
  220. {
  221. _currentTask = null;
  222. if (IsClosed)
  223. {
  224. completion.SetCanceled();
  225. }
  226. else
  227. {
  228. completion.SetResult(charsRead);
  229. }
  230. }
  231. }
  232. }
  233. catch (Exception ex)
  234. {
  235. // In case of any errors, ensure that the completion is completed and the task is set back to null if we switched it
  236. completion.TrySetException(ex);
  237. Interlocked.CompareExchange(ref _currentTask, null, completion.Task);
  238. throw;
  239. }
  240. }
  241. return completion.Task;
  242. }
  243. protected override void Dispose(bool disposing)
  244. {
  245. if (disposing)
  246. {
  247. // Set the textreader as closed
  248. SetClosed();
  249. }
  250. base.Dispose(disposing);
  251. }
  252. /// <summary>
  253. /// Forces the TextReader to act as if it was closed
  254. /// This does not actually close the stream, read off the rest of the data or dispose this
  255. /// </summary>
  256. internal void SetClosed()
  257. {
  258. _disposalTokenSource.Cancel();
  259. _reader = null;
  260. _peekedChar = -1;
  261. // Wait for pending task
  262. var currentTask = _currentTask;
  263. if (currentTask != null)
  264. {
  265. ((IAsyncResult)currentTask).AsyncWaitHandle.WaitOne();
  266. }
  267. }
  268. /// <summary>
  269. /// Performs the actual reading and converting
  270. /// NOTE: This assumes that buffer, index and count are all valid, we're not closed (!IsClosed) and that there is data left (IsDataLeft())
  271. /// </summary>
  272. /// <param name="buffer"></param>
  273. /// <param name="index"></param>
  274. /// <param name="count"></param>
  275. /// <returns></returns>
  276. private int InternalRead(char[] buffer, int index, int count)
  277. {
  278. Debug.Assert(buffer != null, "Null output buffer");
  279. Debug.Assert((index >= 0) && (count >= 0) && (index + count <= buffer.Length), string.Format("Bad count: {0} or index: {1}", count, index));
  280. Debug.Assert(!IsClosed, "Can't read while textreader is closed");
  281. try
  282. {
  283. int byteBufferUsed;
  284. byte[] byteBuffer = PrepareByteBuffer(count, out byteBufferUsed);
  285. byteBufferUsed += _reader.GetBytesInternalSequential(_columnIndex, byteBuffer, byteBufferUsed, byteBuffer.Length - byteBufferUsed);
  286. if (byteBufferUsed > 0) {
  287. return DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, index, count);
  288. }
  289. else {
  290. // Nothing to read, or nothing read
  291. return 0;
  292. }
  293. }
  294. catch (SqlException ex)
  295. {
  296. // Read can't throw a SqlException - so wrap it in an IOException
  297. throw ADP.ErrorReadingFromStream(ex);
  298. }
  299. }
  300. /// <summary>
  301. /// Creates a byte array large enough to store all bytes for the characters in the current encoding, then fills it with any leftover bytes
  302. /// </summary>
  303. /// <param name="numberOfChars">Number of characters that are to be read</param>
  304. /// <param name="byteBufferUsed">Number of bytes pre-filled by the leftover bytes</param>
  305. /// <returns>A byte array of the correct size, pre-filled with leftover bytes</returns>
  306. private byte[] PrepareByteBuffer(int numberOfChars, out int byteBufferUsed)
  307. {
  308. Debug.Assert(numberOfChars >= 0, "Can't prepare a byte buffer for negative characters");
  309. byte[] byteBuffer;
  310. if (numberOfChars == 0)
  311. {
  312. byteBuffer = new byte[0];
  313. byteBufferUsed = 0;
  314. }
  315. else
  316. {
  317. int byteBufferSize = _encoding.GetMaxByteCount(numberOfChars);
  318. if (_leftOverBytes != null)
  319. {
  320. // If we have more leftover bytes than we need for this conversion, then just re-use the leftover buffer
  321. if (_leftOverBytes.Length > byteBufferSize)
  322. {
  323. byteBuffer = _leftOverBytes;
  324. byteBufferUsed = byteBuffer.Length;
  325. }
  326. else
  327. {
  328. // Otherwise, copy over the leftover buffer
  329. byteBuffer = new byte[byteBufferSize];
  330. Array.Copy(_leftOverBytes, byteBuffer, _leftOverBytes.Length);
  331. byteBufferUsed = _leftOverBytes.Length;
  332. }
  333. }
  334. else
  335. {
  336. byteBuffer = new byte[byteBufferSize];
  337. byteBufferUsed = 0;
  338. }
  339. }
  340. return byteBuffer;
  341. }
  342. /// <summary>
  343. /// Decodes the given bytes into characters, and stores the leftover bytes for later use
  344. /// </summary>
  345. /// <param name="inBuffer">Buffer of bytes to decode</param>
  346. /// <param name="inBufferCount">Number of bytes to decode from the inBuffer</param>
  347. /// <param name="outBuffer">Buffer to write the characters to</param>
  348. /// <param name="outBufferOffset">Offset to start writing to outBuffer at</param>
  349. /// <param name="outBufferCount">Maximum number of characters to decode</param>
  350. /// <returns>The actual number of characters decoded</returns>
  351. private int DecodeBytesToChars(byte[] inBuffer, int inBufferCount, char[] outBuffer, int outBufferOffset, int outBufferCount)
  352. {
  353. Debug.Assert(inBuffer != null, "Null input buffer");
  354. Debug.Assert((inBufferCount > 0) && (inBufferCount <= inBuffer.Length), string.Format("Bad inBufferCount: {0}", inBufferCount));
  355. Debug.Assert(outBuffer != null, "Null output buffer");
  356. Debug.Assert((outBufferOffset >= 0) && (outBufferCount > 0) && (outBufferOffset + outBufferCount <= outBuffer.Length), string.Format("Bad outBufferCount: {0} or outBufferOffset: {1}", outBufferCount, outBufferOffset));
  357. int charsRead;
  358. int bytesUsed;
  359. bool completed;
  360. _decoder.Convert(inBuffer, 0, inBufferCount, outBuffer, outBufferOffset, outBufferCount, false, out bytesUsed, out charsRead, out completed);
  361. // completed may be false and there is no spare bytes if the Decoder has stored bytes to use later
  362. if ((!completed) && (bytesUsed < inBufferCount))
  363. {
  364. _leftOverBytes = new byte[inBufferCount - bytesUsed];
  365. Array.Copy(inBuffer, bytesUsed, _leftOverBytes, 0, _leftOverBytes.Length);
  366. }
  367. else
  368. {
  369. // If Convert() sets completed to true, then it must have used all of the bytes we gave it
  370. Debug.Assert(bytesUsed >= inBufferCount, "Converted completed, but not all bytes were used");
  371. _leftOverBytes = null;
  372. }
  373. Debug.Assert(((_reader == null) || (_reader.ColumnDataBytesRemaining() > 0) || (!completed) || (_leftOverBytes == null)), "Stream has run out of data and the decoder finished, but there are leftover bytes");
  374. Debug.Assert(charsRead > 0, "Converted no chars. Bad encoding?");
  375. return charsRead;
  376. }
  377. /// <summary>
  378. /// True if this TextReader is supposed to be closed
  379. /// </summary>
  380. private bool IsClosed
  381. {
  382. get { return (_reader == null); }
  383. }
  384. /// <summary>
  385. /// True if there is data left to read
  386. /// </summary>
  387. /// <returns></returns>
  388. private bool IsDataLeft
  389. {
  390. get { return ((_leftOverBytes != null) || (_reader.ColumnDataBytesRemaining() > 0)); }
  391. }
  392. /// <summary>
  393. /// True if there is a peeked character available
  394. /// </summary>
  395. private bool HasPeekedChar
  396. {
  397. get { return (_peekedChar >= char.MinValue); }
  398. }
  399. /// <summary>
  400. /// Checks the the parameters passed into a Read() method are valid
  401. /// </summary>
  402. /// <param name="buffer"></param>
  403. /// <param name="index"></param>
  404. /// <param name="count"></param>
  405. internal static void ValidateReadParameters(char[] buffer, int index, int count)
  406. {
  407. if (buffer == null)
  408. {
  409. throw ADP.ArgumentNull(ADP.ParameterBuffer);
  410. }
  411. if (index < 0)
  412. {
  413. throw ADP.ArgumentOutOfRange(ADP.ParameterIndex);
  414. }
  415. if (count < 0)
  416. {
  417. throw ADP.ArgumentOutOfRange(ADP.ParameterCount);
  418. }
  419. try
  420. {
  421. if (checked(index + count) > buffer.Length)
  422. {
  423. throw ExceptionBuilder.InvalidOffsetLength();
  424. }
  425. }
  426. catch (OverflowException)
  427. {
  428. // If we've overflowed when adding index and count, then they never would have fit into buffer anyway
  429. throw ExceptionBuilder.InvalidOffsetLength();
  430. }
  431. }
  432. }
  433. sealed internal class SqlUnicodeEncoding : UnicodeEncoding
  434. {
  435. private static SqlUnicodeEncoding _singletonEncoding = new SqlUnicodeEncoding();
  436. private SqlUnicodeEncoding() : base(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: false)
  437. {}
  438. public override Decoder GetDecoder()
  439. {
  440. return new SqlUnicodeDecoder();
  441. }
  442. public override int GetMaxByteCount(int charCount)
  443. {
  444. // SQL Server never sends a BOM, so we can assume that its 2 bytes per char
  445. return charCount * 2;
  446. }
  447. public static Encoding SqlUnicodeEncodingInstance
  448. {
  449. get { return _singletonEncoding; }
  450. }
  451. sealed private class SqlUnicodeDecoder : Decoder
  452. {
  453. public override int GetCharCount(byte[] bytes, int index, int count)
  454. {
  455. // SQL Server never sends a BOM, so we can assume that its 2 bytes per char
  456. return count / 2;
  457. }
  458. public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
  459. {
  460. // This method is required - simply call Convert()
  461. int bytesUsed;
  462. int charsUsed;
  463. bool completed;
  464. Convert(bytes, byteIndex, byteCount, chars, charIndex, chars.Length - charIndex, true, out bytesUsed, out charsUsed, out completed);
  465. return charsUsed;
  466. }
  467. public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed)
  468. {
  469. // Assume 2 bytes per char and no BOM
  470. charsUsed = Math.Min(charCount, byteCount / 2);
  471. bytesUsed = charsUsed * 2;
  472. completed = (bytesUsed == byteCount);
  473. // BlockCopy uses offsets\length measured in bytes, not the actual array index
  474. Buffer.BlockCopy(bytes, byteIndex, chars, charIndex * 2, bytesUsed);
  475. }
  476. }
  477. }
  478. }