Welcome to mirror list, hosted at ThFree Co, Russian Federation.

SqlStream.cs « SqlClient « Data « System « System.Data « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e80bd516e0167e667c9e623b39b2b6158417b9f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//------------------------------------------------------------------------------
// <copyright file="SqlStream.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// <owner current="true" primary="true">Microsoft</owner>
// <owner current="true" primary="false">Microsoft</owner>
//------------------------------------------------------------------------------
namespace System.Data.SqlClient {

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Data.Common;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Xml;
    using System.Reflection;
    using System.Runtime.CompilerServices;

    sealed internal class SqlStream : Stream {
        private SqlDataReader _reader; // reader we will stream off
        private int           _columnOrdinal;
        private long          _bytesCol;
        int                   _bom;
        private byte[]        _bufferedData;
        private bool          _processAllRows;
        private bool          _advanceReader;
        private bool          _readFirstRow = false;
        private bool          _endOfColumn = false;
        
        internal SqlStream(SqlDataReader reader, bool addByteOrderMark, bool processAllRows) :
            this(0, reader, addByteOrderMark, processAllRows, true) {
        }

        internal SqlStream(int columnOrdinal, SqlDataReader reader, bool addByteOrderMark , bool processAllRows, bool advanceReader) {
            _columnOrdinal = columnOrdinal;
            _reader = reader;
            _bom = addByteOrderMark ? 0xfeff : 0;
            _processAllRows = processAllRows;
            _advanceReader = advanceReader;
        }
        
        override public bool CanRead {
            get {
                return true;
            }
        }

        override public bool CanSeek {
            get {
                return false;
            }
        }

        override public bool CanWrite {
            get {
                return false;
            }
        }

        override public long Length {
            get {
              throw ADP.NotSupported();
            }
        }

        override public long Position {
            get {
                throw ADP.NotSupported();
            }
            set {
                throw ADP.NotSupported();
            }
        }

        override protected void Dispose(bool disposing) {
            try {
                if (disposing && _advanceReader && _reader != null && !_reader.IsClosed) {
                    _reader.Close();
                }
                _reader = null;
            }
            finally {
                base.Dispose(disposing);
            }
        }

        override public void Flush() {
            throw ADP.NotSupported();
        }

        override public int Read(byte[] buffer, int offset, int count) {
            int intCount = 0;
            int cBufferedData = 0;
            
            if ((null == _reader)) {  
                throw ADP.StreamClosed(ADP.Read);
            }
            if (null == buffer) {
                throw ADP.ArgumentNull(ADP.ParameterBuffer);
            }
            if ((offset < 0) || (count < 0)) {
                throw ADP.ArgumentOutOfRange(String.Empty, (offset < 0 ? ADP.ParameterOffset : ADP.ParameterCount));
            }
            if (buffer.Length - offset < count) {
                throw ADP.ArgumentOutOfRange(ADP.ParameterCount);
            }
           
            // Need to find out if we should add byte order mark or not. 
            // We need to add this if we are getting ntext xml, not if we are getting binary xml
            // Binary Xml always begins with the bytes 0xDF and 0xFF
            // If we aren't getting these, then we are getting unicode xml
            if (_bom > 0 ) {
                // Read and buffer the first two bytes
                _bufferedData = new byte[2];
                cBufferedData = ReadBytes(_bufferedData, 0, 2);
                // Check to se if we should add the byte order mark
                if ((cBufferedData < 2) || ((_bufferedData[0] == 0xDF) && (_bufferedData[1] == 0xFF))){
                    _bom = 0;
                } 
                while (count > 0) {
                    if (_bom > 0) {
                        buffer[offset] = (byte)_bom;
                        _bom >>= 8;
                        offset++;
                        count--;
                        intCount++;
                    }
                    else {
                        break;
                    }
                }          
            }
           
            if (cBufferedData > 0) {
                while (count > 0) {
                    buffer[offset++] = _bufferedData[0];
                    intCount++;
                    count--;
                    if ((cBufferedData > 1) && (count > 0)) {
                        buffer[offset++] = _bufferedData[1];
                        intCount++;
                        count--;
                        break;
                    }
                }
                _bufferedData = null;
            }

            intCount += ReadBytes(buffer, offset, count);
            
            return intCount;
        }

        private static bool AdvanceToNextRow(SqlDataReader reader) {
            Debug.Assert(reader != null && !reader.IsClosed);

            // this method skips empty result sets
            do {
                if (reader.Read()) {
                    return true;
                }
            } while (reader.NextResult());
            
            // no more rows
            return false;
        }

        private int ReadBytes(byte[] buffer, int offset, int count) {
            bool gotData = true; 
            int intCount = 0;
            int cb = 0;
            
            if (_reader.IsClosed || _endOfColumn) {
                return 0;
            }
            try {
                while (count > 0) {
                    // if I haven't read any bytes, get the next row
                    if (_advanceReader && (0 == _bytesCol)) {
                        gotData = false;

                        if (_readFirstRow && !_processAllRows) {
                            // for XML column, stop processing after the first row
                            // no op here - reader is closed after the end of this loop
                        }
                        else if (AdvanceToNextRow(_reader)) {
                            _readFirstRow = true;

                            if (_reader.IsDBNull(_columnOrdinal)) {
                                // VSTFDEVDIV 479659: handle row with DBNULL as empty data
                                // for XML column, processing is stopped on the next loop since _readFirstRow is true
                                continue;
                            }
                            
                            // the value is not null, read it
                            gotData = true;
                        }
                        // else AdvanceToNextRow has returned false - no more rows or result sets remained, stop processing
                    }

                    if (gotData) {
                        cb = (int) _reader.GetBytesInternal(_columnOrdinal, _bytesCol, buffer, offset, count);

                        if (cb < count) {
                            _bytesCol = 0;
                            gotData = false;
                            if (!_advanceReader) {
                                _endOfColumn = true;
                            }
                        }                        
                        else {
                            Debug.Assert(cb == count);
                            _bytesCol += cb;
                        } 
                    
                        // we are guaranteed that cb is < Int32.Max since we always pass in count which is of type Int32 to
                        // our getbytes interface
                        count -= (int)cb;
                        offset += (int)cb;
                        intCount += (int)cb;
                    }
                    else {
                        break; // no more data available, we are done
                    }
                }
                if (!gotData && _advanceReader) {
                    _reader.Close();    // Need to close the reader if we are done reading
                }
            } 
            catch (Exception e) {
                if (_advanceReader && ADP.IsCatchableExceptionType(e)) {
                    _reader.Close();
                }
                throw;
            }

            return intCount;
        }

        internal XmlReader ToXmlReader() {
            // Dev11 

            return SqlTypes.SqlXml.CreateSqlXmlReader(this, closeInput: true, throwTargetInvocationExceptions: true);
        }
        
        override public long Seek(long offset, SeekOrigin origin) {
            throw ADP.NotSupported();
        }

        override public void SetLength(long value) {
            throw ADP.NotSupported();
        }

        override public void Write(byte[] buffer, int offset, int count) {
            throw ADP.NotSupported();
        }
    }


    // XmlTextReader does not read all the bytes off the network buffers, so we have to cache it here in the random access
    // case. This causes double buffering and is a perf hit, but this is not the high perf way for accessing this type of data.
    // In the case of sequential access, we do not have to do any buffering since the XmlTextReader we return can become 
    // invalid as soon as we move off the current column.
    sealed internal class SqlCachedStream : Stream {
        int          _currentPosition;   // Position within the current array byte
        int          _currentArrayIndex; // Index into the _cachedBytes ArrayList
        List<byte[]> _cachedBytes;
        long         _totalLength;
        
        // Reads off from the network buffer and caches bytes. Only reads one column value in the current row.
        internal SqlCachedStream(SqlCachedBuffer sqlBuf ) {
            _cachedBytes = sqlBuf.CachedBytes;
        }
    
        override public bool CanRead {
            get {
                return true;
            }
        }

        override public bool CanSeek {
            get {
                return true;
            }
        }

        override public bool CanWrite {
            get {
                return false;
            }
        }

        override public long Length {
            get {
                return TotalLength;
            }
        }

        override public long Position {
            get {
                long  pos = 0;
                if (_currentArrayIndex > 0) {
                    for (int ii = 0 ; ii < _currentArrayIndex ; ii++) {
                        pos += _cachedBytes[ii].Length;
                    }
                }
                pos += _currentPosition;
                return pos;
            }
            set {
                if (null == _cachedBytes) {
                    throw ADP.StreamClosed(ADP.ParameterSetPosition);
                }
                SetInternalPosition(value, ADP.ParameterSetPosition);
            }
        }

        override protected void Dispose(bool disposing) {
            try {
                if (disposing && _cachedBytes != null)
                    _cachedBytes.Clear();
                _cachedBytes = null;
                _currentPosition = 0;
                _currentArrayIndex = 0;
                _totalLength = 0;
            }
            finally {
                base.Dispose(disposing);
            }
        }

        override public void Flush() {
            throw ADP.NotSupported();
        }

        override public int Read(byte[] buffer, int offset, int count) {
            int cb;
            int intCount = 0;
            
            if (null == _cachedBytes) {
                throw ADP.StreamClosed(ADP.Read);
            }
            
            if (null == buffer) {
                throw ADP.ArgumentNull(ADP.ParameterBuffer);
            }
            
            if ((offset < 0) || (count < 0)) {
                throw ADP.ArgumentOutOfRange(String.Empty, (offset < 0 ? ADP.ParameterOffset : ADP.ParameterCount));
            }
            
            if (buffer.Length - offset < count) {
                throw ADP.ArgumentOutOfRange(ADP.ParameterCount);
            }
            
            if (_cachedBytes.Count <= _currentArrayIndex) {
                return 0;       // Everything is read!
            }
            
            while (count > 0) {
                if (_cachedBytes[_currentArrayIndex].Length <= _currentPosition) {
                    _currentArrayIndex++;       // We are done reading this chunk, go to next
                    if (_cachedBytes.Count > _currentArrayIndex) {
                        _currentPosition = 0;
                    }
                    else {
                        break;
                    }
                }
                cb = _cachedBytes[_currentArrayIndex].Length - _currentPosition;
                if (cb > count)
                    cb = count;
                Array.Copy(_cachedBytes[_currentArrayIndex], _currentPosition, buffer, offset, cb);

                _currentPosition += cb;
                count -= (int)cb;
                offset += (int)cb;
                intCount += (int)cb;
            }

            return intCount;
        }

        override public long Seek(long offset, SeekOrigin origin) {
            long pos = 0;

            if (null == _cachedBytes) {
                throw ADP.StreamClosed(ADP.Read);
            }
            
            switch(origin)  {
                case SeekOrigin.Begin:
                    SetInternalPosition(offset, ADP.ParameterOffset);
                    break;
					
                case SeekOrigin.Current:
                    pos  =  offset + Position;
                    SetInternalPosition(pos, ADP.ParameterOffset);                    
                    break;
					
                case SeekOrigin.End:
                    pos  = TotalLength + offset;
                    SetInternalPosition(pos, ADP.ParameterOffset);                    
                    break;
					
                default:
                    throw ADP.InvalidSeekOrigin(ADP.ParameterOffset);
            }
            return pos;
        }

        override public void SetLength(long value) {
            throw ADP.NotSupported();
        }

        override public void Write(byte[] buffer, int offset, int count) {
            throw ADP.NotSupported();
        }
        
        private void SetInternalPosition(long lPos, string argumentName) {
            long  pos = lPos;

            if  (pos < 0) {
                throw new ArgumentOutOfRangeException(argumentName);
            }
            for (int ii = 0 ; ii < _cachedBytes.Count ; ii++) {
                if (pos > _cachedBytes[ii].Length) {
                    pos -= _cachedBytes[ii].Length;
                }
                else {
                    _currentArrayIndex = ii;
                    _currentPosition = (int)pos;
                    return;
                }
            }
            if (pos > 0)
                throw new ArgumentOutOfRangeException(argumentName);
        }

        private long TotalLength {
            get {
                if ((_totalLength == 0) && (_cachedBytes != null)) {
                    long pos = 0;
                    for (int ii = 0 ; ii < _cachedBytes.Count ; ii++) {
                        pos += _cachedBytes[ii].Length;
                    }
                    _totalLength = pos;
                }
                return _totalLength;
            }
        }
    }

    sealed internal class SqlStreamingXml {

        int           _columnOrdinal;
        SqlDataReader _reader;
        XmlReader     _xmlReader;
        XmlWriter     _xmlWriter;
        StringWriter  _strWriter;
        long          _charsRemoved;        

        public SqlStreamingXml(int i, SqlDataReader reader) {
            _columnOrdinal = i;
            _reader = reader;
        }

        public void Close() {
            ((IDisposable)_xmlWriter).Dispose();
            ((IDisposable)_xmlReader).Dispose();
            _reader = null;
            _xmlReader = null;
            _xmlWriter = null;
            _strWriter = null;
        }

        public int ColumnOrdinal {
            get {
                return _columnOrdinal;
            }
        }
        
        public long GetChars(long dataIndex, char[] buffer, int bufferIndex, int length) {
            if (_xmlReader == null) {
                SqlStream sqlStream = new SqlStream( _columnOrdinal, _reader, true /* addByteOrderMark */, false /* processAllRows*/, false /*advanceReader*/);
                _xmlReader = sqlStream.ToXmlReader();
                _strWriter = new StringWriter((System.IFormatProvider)null);
                XmlWriterSettings writerSettings = new XmlWriterSettings();
    		    writerSettings.CloseOutput = true;		// close the memory stream when done
		        writerSettings.ConformanceLevel = ConformanceLevel.Fragment;
		        _xmlWriter = XmlWriter.Create(_strWriter, writerSettings);				
            }

            int charsToSkip = 0;
            int cnt = 0;
            if (dataIndex < _charsRemoved) {
                throw ADP.NonSeqByteAccess(dataIndex, _charsRemoved, ADP.GetChars);
            }
            else if (dataIndex > _charsRemoved) {
                charsToSkip = (int)(dataIndex - _charsRemoved);
            }

            // If buffer parameter is null, we have to return -1 since there is no way for us to know the
            // total size up front without reading and converting the XML.
            if (buffer == null) {
                return (long)(-1);
            }
                
            StringBuilder strBldr = _strWriter.GetStringBuilder();
            while (!_xmlReader.EOF) {
                if (strBldr.Length >= (length+ charsToSkip)) {
                    break;
                }
                // Can't call _xmlWriter.WriteNode here, since it reads all of the data in before returning the first char.
                // Do own implementation of WriteNode instead that reads just enough data to return the required number of chars
                //_xmlWriter.WriteNode(_xmlReader, true);
                //  _xmlWriter.Flush();
                WriteXmlElement();
                if (charsToSkip > 0) {
                    // Aggressively remove the characters we want to skip to avoid growing StringBuilder size too much
                    cnt = strBldr.Length < charsToSkip ? strBldr.Length : charsToSkip;
                    strBldr.Remove(0, cnt);
                    charsToSkip -= cnt;
                    _charsRemoved +=(long)cnt;
                }
            }
            
            if (charsToSkip > 0) {
                cnt = strBldr.Length < charsToSkip ? strBldr.Length : charsToSkip;
                strBldr.Remove(0, cnt);
                charsToSkip -= cnt;
                _charsRemoved +=(long)cnt;
            }
            
            if (strBldr.Length == 0) {                    
                return 0;
            }
            // At this point charsToSkip must be 0
            Debug.Assert(charsToSkip == 0);
            
            cnt = strBldr.Length < length ? strBldr.Length : length;
            for (int i = 0 ; i < cnt ; i++) {
                buffer[bufferIndex + i] = strBldr[i];
            }
            // Remove the characters we have already returned
            strBldr.Remove(0, cnt);
            _charsRemoved += (long)cnt;
            return (long)cnt;
        }

        // This method duplicates the work of XmlWriter.WriteNode except that it reads one element at a time 
        // instead of reading the entire node like XmlWriter.
        private void WriteXmlElement() {

            if (_xmlReader.EOF)
                return;
                
            bool canReadChunk = _xmlReader.CanReadValueChunk;
            char[] writeNodeBuffer = null;

            // Constants
            const int WriteNodeBufferSize = 1024;

            _xmlReader.Read();
            switch (_xmlReader.NodeType) {
                case XmlNodeType.Element:
                    _xmlWriter.WriteStartElement(_xmlReader.Prefix, _xmlReader.LocalName, _xmlReader.NamespaceURI);
                    _xmlWriter.WriteAttributes(_xmlReader, true);
                    if (_xmlReader.IsEmptyElement) {
                        _xmlWriter.WriteEndElement();
                        break;
                    }
                    break;
                case XmlNodeType.Text:
                    if (canReadChunk) {
                        if (writeNodeBuffer == null) {
                            writeNodeBuffer = new char[WriteNodeBufferSize];
                        }
                        int read;
                        while ((read = _xmlReader.ReadValueChunk(writeNodeBuffer, 0, WriteNodeBufferSize)) > 0) {
                            _xmlWriter.WriteChars(writeNodeBuffer, 0, read);
                        }
                    }
                    else {
                        _xmlWriter.WriteString(_xmlReader.Value);
                    }
                    break;
                case XmlNodeType.Whitespace:
                case XmlNodeType.SignificantWhitespace:
                    _xmlWriter.WriteWhitespace(_xmlReader.Value);
                    break;
                case XmlNodeType.CDATA:
                    _xmlWriter.WriteCData(_xmlReader.Value);
                    break;
                case XmlNodeType.EntityReference:
                    _xmlWriter.WriteEntityRef(_xmlReader.Name);
                    break;
                case XmlNodeType.XmlDeclaration:
                case XmlNodeType.ProcessingInstruction:
                    _xmlWriter.WriteProcessingInstruction(_xmlReader.Name, _xmlReader.Value);
                    break;
                case XmlNodeType.DocumentType:
                    _xmlWriter.WriteDocType(_xmlReader.Name, _xmlReader.GetAttribute("PUBLIC"), _xmlReader.GetAttribute("SYSTEM"), _xmlReader.Value);
                    break;
                 case XmlNodeType.Comment:
                    _xmlWriter.WriteComment(_xmlReader.Value);
                    break;
                case XmlNodeType.EndElement:
                    _xmlWriter.WriteFullEndElement();
                    break;
            }
            _xmlWriter.Flush();              
        }        
    }   
}