SqlDataReader.cs 212 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791
  1. //------------------------------------------------------------------------------
  2. // <copyright file="SqlDataReader.cs" company="Microsoft">
  3. // Copyright (c) Microsoft Corporation. All rights reserved.
  4. // </copyright>
  5. // <owner current="true" primary="true">[....]</owner>
  6. // <owner current="true" primary="false">[....]</owner>
  7. //------------------------------------------------------------------------------
  8. namespace System.Data.SqlClient {
  9. using System;
  10. using System.Collections;
  11. using System.Collections.Specialized;
  12. using System.ComponentModel;
  13. using System.Data;
  14. using System.Data.Sql;
  15. using System.Data.SqlTypes;
  16. using System.Data.Common;
  17. using System.Data.ProviderBase;
  18. using System.Diagnostics;
  19. using System.Globalization;
  20. using System.IO;
  21. using System.Reflection;
  22. using System.Runtime.CompilerServices;
  23. using System.Threading;
  24. using System.Xml;
  25. using Microsoft.SqlServer.Server;
  26. using System.Threading.Tasks;
  27. public class SqlDataReader : DbDataReader, IDataReader {
  28. private enum ALTROWSTATUS {
  29. Null = 0, // default and after Done
  30. AltRow, // after calling NextResult and the first AltRow is available for read
  31. Done, // after consuming the value (GetValue -> GetValueInternal)
  32. }
  33. internal class SharedState { // parameters needed to execute cleanup from parser
  34. internal int _nextColumnHeaderToRead;
  35. internal int _nextColumnDataToRead;
  36. internal long _columnDataBytesRemaining;
  37. internal bool _dataReady; // ready to ProcessRow
  38. }
  39. internal SharedState _sharedState = new SharedState();
  40. private TdsParser _parser; // TODO: Probably don't need this, since it's on the stateObj
  41. private TdsParserStateObject _stateObj;
  42. private SqlCommand _command;
  43. private SqlConnection _connection;
  44. private int _defaultLCID;
  45. private bool _haltRead; // bool to denote whether we have read first row for single row behavior
  46. private bool _metaDataConsumed;
  47. private bool _browseModeInfoConsumed;
  48. private bool _isClosed;
  49. private bool _isInitialized; // Webdata 104560
  50. private bool _hasRows;
  51. private ALTROWSTATUS _altRowStatus;
  52. private int _recordsAffected = -1;
  53. private long _defaultTimeoutMilliseconds;
  54. private SqlConnectionString.TypeSystem _typeSystem;
  55. // SQLStatistics support
  56. private SqlStatistics _statistics;
  57. private SqlBuffer[] _data; // row buffer, filled in by ReadColumnData()
  58. private SqlStreamingXml _streamingXml; // Used by Getchars on an Xml column for sequential access
  59. // buffers and metadata
  60. private _SqlMetaDataSet _metaData; // current metaData for the stream, it is lazily loaded
  61. private _SqlMetaDataSetCollection _altMetaDataSetCollection;
  62. private FieldNameLookup _fieldNameLookup;
  63. private CommandBehavior _commandBehavior;
  64. private static int _objectTypeCount; // Bid counter
  65. internal readonly int ObjectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
  66. // context
  67. // undone: we may still want to do this...it's nice to pass in an lpvoid (essentially) and just have the reader keep the state
  68. // private object _context = null; // this is never looked at by the stream object. It is used by upper layers who wish
  69. // to remain stateless
  70. // metadata (no explicit table, use 'Table')
  71. private MultiPartTableName[] _tableNames = null;
  72. private string _resetOptionsString;
  73. private int _lastColumnWithDataChunkRead;
  74. private long _columnDataBytesRead; // last byte read by user
  75. private long _columnDataCharsRead; // last char read by user
  76. private char[] _columnDataChars;
  77. private int _columnDataCharsIndex; // Column index that is currently loaded in _columnDataChars
  78. private Task _currentTask;
  79. private Snapshot _snapshot;
  80. private CancellationTokenSource _cancelAsyncOnCloseTokenSource;
  81. private CancellationToken _cancelAsyncOnCloseToken;
  82. // Used for checking if the Type parameter provided to GetValue<T> is an INullable
  83. internal static readonly Type _typeofINullable = typeof(INullable);
  84. private static readonly Type _typeofSqlString = typeof(SqlString);
  85. private SqlSequentialStream _currentStream;
  86. private SqlSequentialTextReader _currentTextReader;
  87. internal SqlDataReader(SqlCommand command, CommandBehavior behavior)
  88. {
  89. SqlConnection.VerifyExecutePermission();
  90. _command = command;
  91. _commandBehavior = behavior;
  92. if (_command != null) {
  93. _defaultTimeoutMilliseconds = (long)command.CommandTimeout * 1000L;
  94. _connection = command.Connection;
  95. if (_connection != null) {
  96. _statistics = _connection.Statistics;
  97. _typeSystem = _connection.TypeSystem;
  98. }
  99. }
  100. _sharedState._dataReady = false;
  101. _metaDataConsumed = false;
  102. _hasRows = false;
  103. _browseModeInfoConsumed = false;
  104. _currentStream = null;
  105. _currentTextReader = null;
  106. _cancelAsyncOnCloseTokenSource = new CancellationTokenSource();
  107. _cancelAsyncOnCloseToken = _cancelAsyncOnCloseTokenSource.Token;
  108. _columnDataCharsIndex = -1;
  109. }
  110. internal bool BrowseModeInfoConsumed {
  111. set {
  112. _browseModeInfoConsumed = value;
  113. }
  114. }
  115. internal SqlCommand Command {
  116. get {
  117. return _command;
  118. }
  119. }
  120. protected SqlConnection Connection {
  121. get {
  122. return _connection;
  123. }
  124. }
  125. override public int Depth {
  126. get {
  127. if (this.IsClosed) {
  128. throw ADP.DataReaderClosed("Depth");
  129. }
  130. return 0;
  131. }
  132. }
  133. // fields/attributes collection
  134. override public int FieldCount {
  135. get {
  136. if (this.IsClosed) {
  137. throw ADP.DataReaderClosed("FieldCount");
  138. }
  139. if (_currentTask != null) {
  140. throw ADP.AsyncOperationPending();
  141. }
  142. if (MetaData == null) {
  143. return 0;
  144. }
  145. return _metaData.Length;
  146. }
  147. }
  148. override public bool HasRows {
  149. get {
  150. if (this.IsClosed) {
  151. throw ADP.DataReaderClosed("HasRows");
  152. }
  153. if (_currentTask != null) {
  154. throw ADP.AsyncOperationPending();
  155. }
  156. return _hasRows;
  157. }
  158. }
  159. override public bool IsClosed {
  160. get {
  161. return _isClosed;
  162. }
  163. }
  164. internal bool IsInitialized {
  165. get {
  166. return _isInitialized;
  167. }
  168. set {
  169. Debug.Assert(value, "attempting to uninitialize a data reader?");
  170. _isInitialized = value;
  171. }
  172. }
  173. // NOTE: For PLP values this indicates the amount of data left in the current chunk (or 0 if there are no more chunks left)
  174. internal long ColumnDataBytesRemaining() {
  175. // If there are an unknown (-1) number of bytes left for a PLP, read its size
  176. if (-1 == _sharedState._columnDataBytesRemaining) {
  177. _sharedState._columnDataBytesRemaining = (long)_parser.PlpBytesLeft(_stateObj);
  178. }
  179. return _sharedState._columnDataBytesRemaining;
  180. }
  181. internal _SqlMetaDataSet MetaData {
  182. get {
  183. if (IsClosed) {
  184. throw ADP.DataReaderClosed("MetaData");
  185. }
  186. // metaData comes in pieces: colmetadata, tabname, colinfo, etc
  187. // if we have any metaData, return it. If we have none,
  188. // then fetch it
  189. if (_metaData == null && !_metaDataConsumed) {
  190. if (_currentTask != null) {
  191. throw SQL.PendingBeginXXXExists();
  192. }
  193. RuntimeHelpers.PrepareConstrainedRegions();
  194. try {
  195. #if DEBUG
  196. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  197. RuntimeHelpers.PrepareConstrainedRegions();
  198. try {
  199. tdsReliabilitySection.Start();
  200. #else
  201. {
  202. #endif //DEBUG
  203. Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  204. if (!TryConsumeMetaData())
  205. {
  206. throw SQL.SynchronousCallMayNotPend();
  207. }
  208. }
  209. #if DEBUG
  210. finally {
  211. tdsReliabilitySection.Stop();
  212. }
  213. #endif //DEBUG
  214. }
  215. catch (System.OutOfMemoryException e) {
  216. _isClosed = true;
  217. if (null != _connection) {
  218. _connection.Abort(e);
  219. }
  220. throw;
  221. }
  222. catch (System.StackOverflowException e) {
  223. _isClosed = true;
  224. if (null != _connection) {
  225. _connection.Abort(e);
  226. }
  227. throw;
  228. }
  229. catch (System.Threading.ThreadAbortException e) {
  230. _isClosed = true;
  231. if (null != _connection) {
  232. _connection.Abort(e);
  233. }
  234. throw;
  235. }
  236. }
  237. return _metaData;
  238. }
  239. }
  240. internal virtual SmiExtendedMetaData[] GetInternalSmiMetaData() {
  241. SmiExtendedMetaData[] metaDataReturn = null;
  242. _SqlMetaDataSet metaData = this.MetaData;
  243. if ( null != metaData && 0 < metaData.Length ) {
  244. metaDataReturn = new SmiExtendedMetaData[metaData.visibleColumns];
  245. for( int index=0; index < metaData.Length; index++ ) {
  246. _SqlMetaData colMetaData = metaData[index];
  247. if ( !colMetaData.isHidden ) {
  248. SqlCollation collation = colMetaData.collation;
  249. string typeSpecificNamePart1 = null;
  250. string typeSpecificNamePart2 = null;
  251. string typeSpecificNamePart3 = null;
  252. if (SqlDbType.Xml == colMetaData.type) {
  253. typeSpecificNamePart1 = colMetaData.xmlSchemaCollectionDatabase;
  254. typeSpecificNamePart2 = colMetaData.xmlSchemaCollectionOwningSchema;
  255. typeSpecificNamePart3 = colMetaData.xmlSchemaCollectionName;
  256. }
  257. else if (SqlDbType.Udt == colMetaData.type) {
  258. Connection.CheckGetExtendedUDTInfo(colMetaData, true); // SQLBUDT #370593 ensure that colMetaData.udtType is set
  259. typeSpecificNamePart1 = colMetaData.udtDatabaseName;
  260. typeSpecificNamePart2 = colMetaData.udtSchemaName;
  261. typeSpecificNamePart3 = colMetaData.udtTypeName;
  262. }
  263. int length = colMetaData.length;
  264. if ( length > TdsEnums.MAXSIZE ) {
  265. length = (int) SmiMetaData.UnlimitedMaxLengthIndicator;
  266. }
  267. else if (SqlDbType.NChar == colMetaData.type
  268. ||SqlDbType.NVarChar == colMetaData.type) {
  269. length /= ADP.CharSize;
  270. }
  271. metaDataReturn[index] = new SmiQueryMetaData(
  272. colMetaData.type,
  273. length,
  274. colMetaData.precision,
  275. colMetaData.scale,
  276. (null != collation) ? collation.LCID : _defaultLCID,
  277. (null != collation) ? collation.SqlCompareOptions : SqlCompareOptions.None,
  278. colMetaData.udtType,
  279. false, // isMultiValued
  280. null, // fieldmetadata
  281. null, // extended properties
  282. colMetaData.column,
  283. typeSpecificNamePart1,
  284. typeSpecificNamePart2,
  285. typeSpecificNamePart3,
  286. colMetaData.isNullable,
  287. colMetaData.serverName,
  288. colMetaData.catalogName,
  289. colMetaData.schemaName,
  290. colMetaData.tableName,
  291. colMetaData.baseColumn,
  292. colMetaData.isKey,
  293. colMetaData.isIdentity,
  294. 0==colMetaData.updatability,
  295. colMetaData.isExpression,
  296. colMetaData.isDifferentName,
  297. colMetaData.isHidden
  298. );
  299. }
  300. }
  301. }
  302. return metaDataReturn;
  303. }
  304. override public int RecordsAffected {
  305. get {
  306. if (null != _command)
  307. return _command.InternalRecordsAffected;
  308. // cached locally for after Close() when command is nulled out
  309. return _recordsAffected;
  310. }
  311. }
  312. internal string ResetOptionsString {
  313. set {
  314. _resetOptionsString = value;
  315. }
  316. }
  317. private SqlStatistics Statistics {
  318. get {
  319. return _statistics;
  320. }
  321. }
  322. internal MultiPartTableName[] TableNames {
  323. get {
  324. return _tableNames;
  325. }
  326. set {
  327. _tableNames = value;
  328. }
  329. }
  330. override public int VisibleFieldCount {
  331. get {
  332. if (this.IsClosed) {
  333. throw ADP.DataReaderClosed("VisibleFieldCount");
  334. }
  335. _SqlMetaDataSet md = this.MetaData;
  336. if (md == null) {
  337. return 0;
  338. }
  339. return (md.visibleColumns);
  340. }
  341. }
  342. // this operator
  343. override public object this[int i] {
  344. get {
  345. return GetValue(i);
  346. }
  347. }
  348. override public object this[string name] {
  349. get {
  350. return GetValue(GetOrdinal(name));
  351. }
  352. }
  353. internal void Bind(TdsParserStateObject stateObj) {
  354. Debug.Assert(null != stateObj, "null stateobject");
  355. Debug.Assert(null == _snapshot, "Should not change during execution of asynchronous command");
  356. stateObj.Owner = this;
  357. _stateObj = stateObj;
  358. _parser = stateObj.Parser;
  359. _defaultLCID = _parser.DefaultLCID;
  360. }
  361. // Fills in a schema table with meta data information. This function should only really be called by
  362. //
  363. internal DataTable BuildSchemaTable() {
  364. _SqlMetaDataSet md = this.MetaData;
  365. Debug.Assert(null != md, "BuildSchemaTable - unexpected null metadata information");
  366. DataTable schemaTable = new DataTable("SchemaTable");
  367. schemaTable.Locale = CultureInfo.InvariantCulture;
  368. schemaTable.MinimumCapacity = md.Length;
  369. DataColumn ColumnName = new DataColumn(SchemaTableColumn.ColumnName, typeof(System.String));
  370. DataColumn Ordinal = new DataColumn(SchemaTableColumn.ColumnOrdinal, typeof(System.Int32));
  371. DataColumn Size = new DataColumn(SchemaTableColumn.ColumnSize, typeof(System.Int32));
  372. DataColumn Precision = new DataColumn(SchemaTableColumn.NumericPrecision, typeof(System.Int16));
  373. DataColumn Scale = new DataColumn(SchemaTableColumn.NumericScale, typeof(System.Int16));
  374. DataColumn DataType = new DataColumn(SchemaTableColumn.DataType, typeof(System.Type));
  375. DataColumn ProviderSpecificDataType = new DataColumn(SchemaTableOptionalColumn.ProviderSpecificDataType, typeof(System.Type));
  376. DataColumn NonVersionedProviderType = new DataColumn(SchemaTableColumn.NonVersionedProviderType, typeof(System.Int32));
  377. DataColumn ProviderType = new DataColumn(SchemaTableColumn.ProviderType, typeof(System.Int32));
  378. DataColumn IsLong = new DataColumn(SchemaTableColumn.IsLong, typeof(System.Boolean));
  379. DataColumn AllowDBNull = new DataColumn(SchemaTableColumn.AllowDBNull, typeof(System.Boolean));
  380. DataColumn IsReadOnly = new DataColumn(SchemaTableOptionalColumn.IsReadOnly, typeof(System.Boolean));
  381. DataColumn IsRowVersion = new DataColumn(SchemaTableOptionalColumn.IsRowVersion, typeof(System.Boolean));
  382. DataColumn IsUnique = new DataColumn(SchemaTableColumn.IsUnique, typeof(System.Boolean));
  383. DataColumn IsKey = new DataColumn(SchemaTableColumn.IsKey, typeof(System.Boolean));
  384. DataColumn IsAutoIncrement = new DataColumn(SchemaTableOptionalColumn.IsAutoIncrement, typeof(System.Boolean));
  385. DataColumn IsHidden = new DataColumn(SchemaTableOptionalColumn.IsHidden, typeof(System.Boolean));
  386. DataColumn BaseCatalogName = new DataColumn(SchemaTableOptionalColumn.BaseCatalogName, typeof(System.String));
  387. DataColumn BaseSchemaName = new DataColumn(SchemaTableColumn.BaseSchemaName, typeof(System.String));
  388. DataColumn BaseTableName = new DataColumn(SchemaTableColumn.BaseTableName, typeof(System.String));
  389. DataColumn BaseColumnName = new DataColumn(SchemaTableColumn.BaseColumnName, typeof(System.String));
  390. // unique to SqlClient
  391. DataColumn BaseServerName = new DataColumn(SchemaTableOptionalColumn.BaseServerName, typeof(System.String));
  392. DataColumn IsAliased = new DataColumn(SchemaTableColumn.IsAliased, typeof(System.Boolean));
  393. DataColumn IsExpression = new DataColumn(SchemaTableColumn.IsExpression, typeof(System.Boolean));
  394. DataColumn IsIdentity = new DataColumn("IsIdentity", typeof(System.Boolean));
  395. DataColumn DataTypeName = new DataColumn("DataTypeName", typeof(System.String));
  396. DataColumn UdtAssemblyQualifiedName = new DataColumn("UdtAssemblyQualifiedName", typeof(System.String));
  397. // Xml metadata specific
  398. DataColumn XmlSchemaCollectionDatabase = new DataColumn("XmlSchemaCollectionDatabase", typeof(System.String));
  399. DataColumn XmlSchemaCollectionOwningSchema = new DataColumn("XmlSchemaCollectionOwningSchema", typeof(System.String));
  400. DataColumn XmlSchemaCollectionName = new DataColumn("XmlSchemaCollectionName", typeof(System.String));
  401. // SparseColumnSet
  402. DataColumn IsColumnSet = new DataColumn("IsColumnSet", typeof(System.Boolean));
  403. Ordinal.DefaultValue = 0;
  404. IsLong.DefaultValue = false;
  405. DataColumnCollection columns = schemaTable.Columns;
  406. // must maintain order for backward compatibility
  407. columns.Add(ColumnName);
  408. columns.Add(Ordinal);
  409. columns.Add(Size);
  410. columns.Add(Precision);
  411. columns.Add(Scale);
  412. columns.Add(IsUnique);
  413. columns.Add(IsKey);
  414. columns.Add(BaseServerName);
  415. columns.Add(BaseCatalogName);
  416. columns.Add(BaseColumnName);
  417. columns.Add(BaseSchemaName);
  418. columns.Add(BaseTableName);
  419. columns.Add(DataType);
  420. columns.Add(AllowDBNull);
  421. columns.Add(ProviderType);
  422. columns.Add(IsAliased);
  423. columns.Add(IsExpression);
  424. columns.Add(IsIdentity);
  425. columns.Add(IsAutoIncrement);
  426. columns.Add(IsRowVersion);
  427. columns.Add(IsHidden);
  428. columns.Add(IsLong);
  429. columns.Add(IsReadOnly);
  430. columns.Add(ProviderSpecificDataType);
  431. columns.Add(DataTypeName);
  432. columns.Add(XmlSchemaCollectionDatabase);
  433. columns.Add(XmlSchemaCollectionOwningSchema);
  434. columns.Add(XmlSchemaCollectionName);
  435. columns.Add(UdtAssemblyQualifiedName);
  436. columns.Add(NonVersionedProviderType);
  437. columns.Add(IsColumnSet);
  438. for (int i = 0; i < md.Length; i++) {
  439. _SqlMetaData col = md[i];
  440. DataRow schemaRow = schemaTable.NewRow();
  441. schemaRow[ColumnName] = col.column;
  442. schemaRow[Ordinal] = col.ordinal;
  443. //
  444. // be sure to return character count for string types, byte count otherwise
  445. // col.length is always byte count so for unicode types, half the length
  446. //
  447. // For MAX and XML datatypes, we get 0x7fffffff from the server. Do not divide this.
  448. if (col.cipherMD != null) {
  449. Debug.Assert(col.baseTI != null && col.baseTI.metaType != null, "col.baseTI and col.baseTI.metaType should not be null.");
  450. schemaRow[Size] = (col.baseTI.metaType.IsSizeInCharacters && (col.baseTI.length != 0x7fffffff)) ? (col.baseTI.length / 2) : col.baseTI.length;
  451. }
  452. else {
  453. schemaRow[Size] = (col.metaType.IsSizeInCharacters && (col.length != 0x7fffffff)) ? (col.length / 2) : col.length;
  454. }
  455. schemaRow[DataType] = GetFieldTypeInternal(col);
  456. schemaRow[ProviderSpecificDataType] = GetProviderSpecificFieldTypeInternal(col);
  457. schemaRow[NonVersionedProviderType] = (int) (col.cipherMD != null ? col.baseTI.type : col.type); // SqlDbType enum value - does not change with TypeSystem.
  458. schemaRow[DataTypeName] = GetDataTypeNameInternal(col);
  459. if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && col.IsNewKatmaiDateTimeType) {
  460. schemaRow[ProviderType] = SqlDbType.NVarChar;
  461. switch (col.type) {
  462. case SqlDbType.Date:
  463. schemaRow[Size] = TdsEnums.WHIDBEY_DATE_LENGTH;
  464. break;
  465. case SqlDbType.Time:
  466. Debug.Assert(TdsEnums.UNKNOWN_PRECISION_SCALE == col.scale || (0 <= col.scale && col.scale <= 7), "Invalid scale for Time column: " + col.scale);
  467. schemaRow[Size] = TdsEnums.WHIDBEY_TIME_LENGTH[TdsEnums.UNKNOWN_PRECISION_SCALE != col.scale ? col.scale : col.metaType.Scale];
  468. break;
  469. case SqlDbType.DateTime2:
  470. Debug.Assert(TdsEnums.UNKNOWN_PRECISION_SCALE == col.scale || (0 <= col.scale && col.scale <= 7), "Invalid scale for DateTime2 column: " + col.scale);
  471. schemaRow[Size] = TdsEnums.WHIDBEY_DATETIME2_LENGTH[TdsEnums.UNKNOWN_PRECISION_SCALE != col.scale ? col.scale : col.metaType.Scale];
  472. break;
  473. case SqlDbType.DateTimeOffset:
  474. Debug.Assert(TdsEnums.UNKNOWN_PRECISION_SCALE == col.scale || (0 <= col.scale && col.scale <= 7), "Invalid scale for DateTimeOffset column: " + col.scale);
  475. schemaRow[Size] = TdsEnums.WHIDBEY_DATETIMEOFFSET_LENGTH[TdsEnums.UNKNOWN_PRECISION_SCALE != col.scale ? col.scale : col.metaType.Scale];
  476. break;
  477. }
  478. }
  479. else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && col.IsLargeUdt) {
  480. if (_typeSystem == SqlConnectionString.TypeSystem.SQLServer2005) {
  481. schemaRow[ProviderType] = SqlDbType.VarBinary;
  482. }
  483. else {
  484. // TypeSystem.SQLServer2000
  485. schemaRow[ProviderType] = SqlDbType.Image;
  486. }
  487. }
  488. else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000) {
  489. // TypeSystem.SQLServer2005 and above
  490. // SqlDbType enum value - always the actual type for SQLServer2005.
  491. schemaRow[ProviderType] = (int) (col.cipherMD != null ? col.baseTI.type : col.type);
  492. if (col.type == SqlDbType.Udt) { // Additional metadata for UDTs.
  493. Debug.Assert(Connection.IsYukonOrNewer, "Invalid Column type received from the server");
  494. schemaRow[UdtAssemblyQualifiedName] = col.udtAssemblyQualifiedName;
  495. }
  496. else if (col.type == SqlDbType.Xml) { // Additional metadata for Xml.
  497. Debug.Assert(Connection.IsYukonOrNewer, "Invalid DataType (Xml) for the column");
  498. schemaRow[XmlSchemaCollectionDatabase] = col.xmlSchemaCollectionDatabase;
  499. schemaRow[XmlSchemaCollectionOwningSchema] = col.xmlSchemaCollectionOwningSchema;
  500. schemaRow[XmlSchemaCollectionName] = col.xmlSchemaCollectionName;
  501. }
  502. }
  503. else {
  504. // TypeSystem.SQLServer2000
  505. // SqlDbType enum value - variable for certain types when SQLServer2000.
  506. schemaRow[ProviderType] = GetVersionedMetaType(col.metaType).SqlDbType;
  507. }
  508. if (col.cipherMD != null) {
  509. Debug.Assert(col.baseTI != null, @"col.baseTI should not be null.");
  510. if (TdsEnums.UNKNOWN_PRECISION_SCALE != col.baseTI.precision) {
  511. schemaRow[Precision] = col.baseTI.precision;
  512. }
  513. else {
  514. schemaRow[Precision] = col.baseTI.metaType.Precision;
  515. }
  516. }
  517. else if (TdsEnums.UNKNOWN_PRECISION_SCALE != col.precision) {
  518. schemaRow[Precision] = col.precision;
  519. }
  520. else {
  521. schemaRow[Precision] = col.metaType.Precision;
  522. }
  523. if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && col.IsNewKatmaiDateTimeType) {
  524. schemaRow[Scale] = MetaType.MetaNVarChar.Scale;
  525. }
  526. else if (col.cipherMD != null) {
  527. Debug.Assert(col.baseTI != null, @"col.baseTI should not be null.");
  528. if (TdsEnums.UNKNOWN_PRECISION_SCALE != col.baseTI.scale) {
  529. schemaRow[Scale] = col.baseTI.scale;
  530. }
  531. else {
  532. schemaRow[Scale] = col.baseTI.metaType.Scale;
  533. }
  534. }
  535. else if (TdsEnums.UNKNOWN_PRECISION_SCALE != col.scale) {
  536. schemaRow[Scale] = col.scale;
  537. }
  538. else {
  539. schemaRow[Scale] = col.metaType.Scale;
  540. }
  541. schemaRow[AllowDBNull] = col.isNullable;
  542. // If no ColInfo token received, do not set value, leave as null.
  543. if (_browseModeInfoConsumed) {
  544. schemaRow[IsAliased] = col.isDifferentName;
  545. schemaRow[IsKey] = col.isKey;
  546. schemaRow[IsHidden] = col.isHidden;
  547. schemaRow[IsExpression] = col.isExpression;
  548. }
  549. schemaRow[IsIdentity] = col.isIdentity;
  550. schemaRow[IsAutoIncrement] = col.isIdentity;
  551. if (col.cipherMD != null) {
  552. Debug.Assert(col.baseTI != null, @"col.baseTI should not be null.");
  553. Debug.Assert(col.baseTI.metaType != null, @"col.baseTI.metaType should not be null.");
  554. schemaRow[IsLong] = col.baseTI.metaType.IsLong;
  555. }
  556. else {
  557. schemaRow[IsLong] = col.metaType.IsLong;
  558. }
  559. // mark unique for timestamp columns
  560. if (SqlDbType.Timestamp == col.type) {
  561. schemaRow[IsUnique] = true;
  562. schemaRow[IsRowVersion] = true;
  563. }
  564. else {
  565. schemaRow[IsUnique] = false;
  566. schemaRow[IsRowVersion] = false;
  567. }
  568. schemaRow[IsReadOnly] = (0 == col.updatability);
  569. schemaRow[IsColumnSet] = col.isColumnSet;
  570. if (!ADP.IsEmpty(col.serverName)) {
  571. schemaRow[BaseServerName] = col.serverName;
  572. }
  573. if (!ADP.IsEmpty(col.catalogName)) {
  574. schemaRow[BaseCatalogName] = col.catalogName;
  575. }
  576. if (!ADP.IsEmpty(col.schemaName)) {
  577. schemaRow[BaseSchemaName] = col.schemaName;
  578. }
  579. if (!ADP.IsEmpty(col.tableName)) {
  580. schemaRow[BaseTableName] = col.tableName;
  581. }
  582. if (!ADP.IsEmpty(col.baseColumn)) {
  583. schemaRow[BaseColumnName] = col.baseColumn;
  584. }
  585. else if (!ADP.IsEmpty(col.column)) {
  586. schemaRow[BaseColumnName] = col.column;
  587. }
  588. schemaTable.Rows.Add(schemaRow);
  589. schemaRow.AcceptChanges();
  590. }
  591. // mark all columns as readonly
  592. foreach(DataColumn column in columns) {
  593. column.ReadOnly = true; // MDAC 70943
  594. }
  595. return schemaTable;
  596. }
  597. internal void Cancel(int objectID) {
  598. TdsParserStateObject stateObj = _stateObj;
  599. if (null != stateObj) {
  600. stateObj.Cancel(objectID);
  601. }
  602. }
  603. // wipe any data off the wire from a partial read
  604. // and reset all pointers for sequential access
  605. private bool TryCleanPartialRead() {
  606. AssertReaderState(requireData: true, permitAsync: true);
  607. // VSTS DEVDIV2 380446: It is possible that read attempt we are cleaning after ended with partially
  608. // processed header (if it falls between network packets). In this case the first thing to do is to
  609. // finish reading the header, otherwise code will start treating unread header as TDS payload.
  610. if (_stateObj._partialHeaderBytesRead > 0) {
  611. if (!_stateObj.TryProcessHeader()) {
  612. return false;
  613. }
  614. }
  615. // following cases for sequential read
  616. // i. user called read but didn't fetch anything
  617. // iia. user called read and fetched a subset of the columns
  618. // iib. user called read and fetched a subset of the column data
  619. // Wipe out any Streams or TextReaders
  620. if (-1 != _lastColumnWithDataChunkRead) {
  621. CloseActiveSequentialStreamAndTextReader();
  622. }
  623. // i. user called read but didn't fetch anything
  624. if (0 == _sharedState._nextColumnHeaderToRead) {
  625. if (!_stateObj.Parser.TrySkipRow(_metaData, _stateObj)) {
  626. return false;
  627. }
  628. }
  629. else {
  630. // iia. if we still have bytes left from a partially read column, skip
  631. if (!TryResetBlobState()) {
  632. return false;
  633. }
  634. // iib.
  635. // now read the remaining values off the wire for this row
  636. if (!_stateObj.Parser.TrySkipRow(_metaData, _sharedState._nextColumnHeaderToRead, _stateObj)) {
  637. return false;
  638. }
  639. }
  640. #if DEBUG
  641. if (_stateObj._pendingData) {
  642. byte token;
  643. if (!_stateObj.TryPeekByte(out token)) {
  644. return false;
  645. }
  646. Debug.Assert(TdsParser.IsValidTdsToken(token), string.Format("Invalid token after performing CleanPartialRead: {0,-2:X2}", token));
  647. }
  648. #endif
  649. _sharedState._dataReady = false;
  650. return true;
  651. }
  652. private void CleanPartialReadReliable() {
  653. AssertReaderState(requireData: true, permitAsync: false);
  654. RuntimeHelpers.PrepareConstrainedRegions();
  655. try {
  656. #if DEBUG
  657. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  658. RuntimeHelpers.PrepareConstrainedRegions();
  659. try {
  660. tdsReliabilitySection.Start();
  661. #else
  662. {
  663. #endif //DEBUG
  664. bool result = TryCleanPartialRead();
  665. Debug.Assert(result, "Should not pend on sync call");
  666. Debug.Assert(!_sharedState._dataReady, "_dataReady should be cleared");
  667. }
  668. #if DEBUG
  669. finally {
  670. tdsReliabilitySection.Stop();
  671. }
  672. #endif //DEBUG
  673. }
  674. catch (System.OutOfMemoryException e) {
  675. _isClosed = true;
  676. if (_connection != null) {
  677. _connection.Abort(e);
  678. }
  679. throw;
  680. }
  681. catch (System.StackOverflowException e) {
  682. _isClosed = true;
  683. if (_connection != null) {
  684. _connection.Abort(e);
  685. }
  686. throw;
  687. }
  688. catch (System.Threading.ThreadAbortException e) {
  689. _isClosed = true;
  690. if (_connection != null) {
  691. _connection.Abort(e);
  692. }
  693. throw;
  694. }
  695. }
  696. override public void Close() {
  697. SqlStatistics statistics = null;
  698. IntPtr hscp;
  699. Bid.ScopeEnter(out hscp, "<sc.SqlDataReader.Close|API> %d#", ObjectID);
  700. try {
  701. statistics = SqlStatistics.StartTimer(Statistics);
  702. TdsParserStateObject stateObj = _stateObj;
  703. // Request that the current task is stopped
  704. _cancelAsyncOnCloseTokenSource.Cancel();
  705. var currentTask = _currentTask;
  706. if ((currentTask != null) && (!currentTask.IsCompleted)) {
  707. try {
  708. // Wait for the task to complete
  709. ((IAsyncResult)currentTask).AsyncWaitHandle.WaitOne();
  710. // Ensure that we've finished reading any pending data
  711. var networkPacketTaskSource = stateObj._networkPacketTaskSource;
  712. if (networkPacketTaskSource != null) {
  713. ((IAsyncResult)networkPacketTaskSource.Task).AsyncWaitHandle.WaitOne();
  714. }
  715. }
  716. catch (Exception) {
  717. // If we receive any exceptions while waiting, something has gone horribly wrong and we need to doom the connection and fast-fail the reader
  718. _connection.InnerConnection.DoomThisConnection();
  719. _isClosed = true;
  720. if (stateObj != null) {
  721. lock (stateObj) {
  722. _stateObj = null;
  723. _command = null;
  724. _connection = null;
  725. }
  726. }
  727. throw;
  728. }
  729. }
  730. // Close down any active Streams and TextReaders (this will also wait for them to finish their async tasks)
  731. // NOTE: This must be done outside of the lock on the stateObj otherwise it will deadlock with CleanupAfterAsyncInvocation
  732. CloseActiveSequentialStreamAndTextReader();
  733. if (stateObj != null) {
  734. // protect against concurrent close and cancel
  735. lock (stateObj) {
  736. if (_stateObj != null ) { // reader not closed while we waited for the lock
  737. // TryCloseInternal will clear out the snapshot when it is done
  738. if (_snapshot != null) {
  739. #if DEBUG
  740. // The stack trace for replays will differ since they weren't captured during close
  741. stateObj._permitReplayStackTraceToDiffer = true;
  742. #endif
  743. PrepareForAsyncContinuation();
  744. }
  745. SetTimeout(_defaultTimeoutMilliseconds);
  746. // Close can be called from async methods in error cases,
  747. // in which case we need to switch to syncOverAsync
  748. stateObj._syncOverAsync = true;
  749. if (!TryCloseInternal(true /*closeReader*/)) {
  750. throw SQL.SynchronousCallMayNotPend();
  751. }
  752. // DO NOT USE stateObj after this point - it has been returned to the TdsParser's session pool and potentially handed out to another thread
  753. }
  754. }
  755. }
  756. }
  757. finally {
  758. SqlStatistics.StopTimer(statistics);
  759. Bid.ScopeLeave(ref hscp);
  760. }
  761. }
  762. private bool TryCloseInternal(bool closeReader) {
  763. TdsParser parser = _parser;
  764. TdsParserStateObject stateObj = _stateObj;
  765. bool closeConnection = (IsCommandBehavior(CommandBehavior.CloseConnection));
  766. bool aborting = false;
  767. bool cleanDataFailed = false;
  768. RuntimeHelpers.PrepareConstrainedRegions();
  769. try {
  770. #if DEBUG
  771. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  772. RuntimeHelpers.PrepareConstrainedRegions();
  773. try {
  774. tdsReliabilitySection.Start();
  775. #else
  776. {
  777. #endif //DEBUG
  778. if ((!_isClosed) && (parser != null) && (stateObj != null) && (stateObj._pendingData)) {
  779. // It is possible for this to be called during connection close on a
  780. // broken connection, so check state first.
  781. if (parser.State == TdsParserState.OpenLoggedIn) {
  782. // if user called read but didn't fetch any values, skip the row
  783. // same applies after NextResult on ALTROW because NextResult starts rowconsumption in that case ...
  784. Debug.Assert(SniContext.Snix_Read==stateObj.SniContext, String.Format((IFormatProvider)null, "The SniContext should be Snix_Read but it actually is {0}", stateObj.SniContext));
  785. if (_altRowStatus == ALTROWSTATUS.AltRow) {
  786. _sharedState._dataReady = true; // set _sharedState._dataReady to not confuse CleanPartialRead
  787. }
  788. _stateObj._internalTimeout = false;
  789. if (_sharedState._dataReady) {
  790. cleanDataFailed = true;
  791. if (TryCleanPartialRead()) {
  792. cleanDataFailed = false;
  793. }
  794. else {
  795. return false;
  796. }
  797. }
  798. #if DEBUG
  799. else {
  800. byte token;
  801. if (!_stateObj.TryPeekByte(out token)) {
  802. return false;
  803. }
  804. Debug.Assert(TdsParser.IsValidTdsToken(token), string.Format("DataReady is false, but next token is invalid: {0,-2:X2}", token));
  805. }
  806. #endif
  807. bool ignored;
  808. if (!parser.TryRun(RunBehavior.Clean, _command, this, null, stateObj, out ignored)) {
  809. return false;
  810. }
  811. }
  812. }
  813. RestoreServerSettings(parser, stateObj);
  814. return true;
  815. }
  816. #if DEBUG
  817. finally {
  818. tdsReliabilitySection.Stop();
  819. }
  820. #endif //DEBUG
  821. }
  822. catch (System.OutOfMemoryException e) {
  823. _isClosed = true;
  824. aborting = true;
  825. if (null != _connection) {
  826. _connection.Abort(e);
  827. }
  828. throw;
  829. }
  830. catch (System.StackOverflowException e) {
  831. _isClosed = true;
  832. aborting = true;
  833. if (null != _connection) {
  834. _connection.Abort(e);
  835. }
  836. throw;
  837. }
  838. catch (System.Threading.ThreadAbortException e) {
  839. _isClosed = true;
  840. aborting = true;
  841. if (null != _connection) {
  842. _connection.Abort(e);
  843. }
  844. throw;
  845. }
  846. finally {
  847. if (aborting) {
  848. _isClosed = true;
  849. _command = null; // we are done at this point, don't allow navigation to the connection
  850. _connection = null;
  851. _statistics = null;
  852. _stateObj = null;
  853. _parser = null;
  854. }
  855. else if (closeReader) {
  856. bool wasClosed = _isClosed;
  857. _isClosed = true;
  858. _parser = null;
  859. _stateObj = null;
  860. _data = null;
  861. if (_snapshot != null) {
  862. CleanupAfterAsyncInvocationInternal(stateObj);
  863. }
  864. // SQLBUDT #284712 - Note the order here is extremely important:
  865. //
  866. // (1) First, we remove the reader from the reference collection
  867. // to prevent it from being forced closed by the parser if
  868. // any future work occurs.
  869. //
  870. // (2) Next, we ensure that cancellation can no longer happen by
  871. // calling CloseSession.
  872. if (Connection != null) {
  873. Connection.RemoveWeakReference(this); // This doesn't catch everything -- the connection may be closed, but it prevents dead readers from clogging the collection
  874. }
  875. RuntimeHelpers.PrepareConstrainedRegions();
  876. try {
  877. #if DEBUG
  878. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  879. RuntimeHelpers.PrepareConstrainedRegions();
  880. try {
  881. tdsReliabilitySection.Start();
  882. #else
  883. {
  884. #endif //DEBUG
  885. // IsClosed may be true if CloseReaderFromConnection was called - in which case, the session has already been closed
  886. if ((!wasClosed) && (null != stateObj)) {
  887. if (!cleanDataFailed) {
  888. stateObj.CloseSession();
  889. }
  890. else {
  891. if (parser != null) {
  892. parser.State = TdsParserState.Broken; // We failed while draining data, so TDS pointer can be between tokens - cannot recover
  893. parser.PutSession(stateObj);
  894. parser.Connection.BreakConnection();
  895. }
  896. }
  897. }
  898. // DO NOT USE stateObj after this point - it has been returned to the TdsParser's session pool and potentially handed out to another thread
  899. }
  900. #if DEBUG
  901. finally {
  902. tdsReliabilitySection.Stop();
  903. }
  904. #endif //DEBUG
  905. }
  906. catch (System.OutOfMemoryException e) {
  907. if (null != _connection) {
  908. _connection.Abort(e);
  909. }
  910. throw;
  911. }
  912. catch (System.StackOverflowException e) {
  913. if (null != _connection) {
  914. _connection.Abort(e);
  915. }
  916. throw;
  917. }
  918. catch (System.Threading.ThreadAbortException e) {
  919. if (null != _connection) {
  920. _connection.Abort(e);
  921. }
  922. throw;
  923. }
  924. // do not retry here
  925. bool result = TrySetMetaData(null, false);
  926. Debug.Assert(result, "Should not pend a synchronous request");
  927. _fieldNameLookup = null;
  928. // if the user calls ExecuteReader(CommandBehavior.CloseConnection)
  929. // then we close down the connection when we are done reading results
  930. if (closeConnection) {
  931. if (Connection != null) {
  932. Connection.Close();
  933. }
  934. }
  935. if (_command != null) {
  936. // cache recordsaffected to be returnable after DataReader.Close();
  937. _recordsAffected = _command.InternalRecordsAffected;
  938. }
  939. _command = null; // we are done at this point, don't allow navigation to the connection
  940. _connection = null;
  941. _statistics = null;
  942. }
  943. }
  944. }
  945. virtual internal void CloseReaderFromConnection() {
  946. var parser = _parser;
  947. Debug.Assert(parser == null || parser.State != TdsParserState.OpenNotLoggedIn, "Reader on a connection that is not logged in");
  948. if ((parser != null) && (parser.State == TdsParserState.OpenLoggedIn)) {
  949. // Connection is ok - proper cleanup
  950. // NOTE: This is NOT thread-safe
  951. Close();
  952. }
  953. else {
  954. // Connection is broken - quick cleanup
  955. // NOTE: This MUST be thread-safe as a broken connection can happen at any time
  956. var stateObj = _stateObj;
  957. _isClosed = true;
  958. // Request that the current task is stopped
  959. _cancelAsyncOnCloseTokenSource.Cancel();
  960. if (stateObj != null) {
  961. var networkPacketTaskSource = stateObj._networkPacketTaskSource;
  962. if (networkPacketTaskSource != null) {
  963. // If the connection is closed or broken, this will never complete
  964. networkPacketTaskSource.TrySetException(ADP.ClosedConnectionError());
  965. }
  966. if (_snapshot != null) {
  967. // CleanWire will do cleanup - so we don't really care about the snapshot
  968. CleanupAfterAsyncInvocationInternal(stateObj, resetNetworkPacketTaskSource: false);
  969. }
  970. // Switch to [....] to prepare for cleanwire
  971. stateObj._syncOverAsync = true;
  972. // Remove owner (this will allow the stateObj to be disposed after the connection is closed)
  973. stateObj.RemoveOwner();
  974. }
  975. }
  976. }
  977. private bool TryConsumeMetaData() {
  978. // warning: Don't check the MetaData property within this function
  979. // warning: as it will be a reentrant call
  980. while (_parser != null && _stateObj != null && _stateObj._pendingData && !_metaDataConsumed) {
  981. if (_parser.State == TdsParserState.Broken || _parser.State == TdsParserState.Closed) {
  982. // Happened for DEVDIV2:180509 (SqlDataReader.ConsumeMetaData Hangs In 100% CPU Loop Forever When TdsParser._state == TdsParserState.Broken)
  983. // during request for DTC address.
  984. // NOTE: We doom connection for TdsParserState.Closed since it indicates that it is in some abnormal and unstable state, probably as a result of
  985. // closing from another thread. In general, TdsParserState.Closed does not necessitate dooming the connection.
  986. if (_parser.Connection != null)
  987. _parser.Connection.DoomThisConnection();
  988. throw SQL.ConnectionDoomed();
  989. }
  990. bool ignored;
  991. if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, this, null, _stateObj, out ignored)) {
  992. return false;
  993. }
  994. Debug.Assert(!ignored, "Parser read a row token while trying to read metadata");
  995. }
  996. // we hide hidden columns from the user so build an internal map
  997. // that compacts all hidden columns from the array
  998. if (null != _metaData) {
  999. if (_snapshot != null && object.ReferenceEquals(_snapshot._metadata, _metaData)) {
  1000. _metaData = (_SqlMetaDataSet)_metaData.Clone();
  1001. }
  1002. _metaData.visibleColumns = 0;
  1003. Debug.Assert(null == _metaData.indexMap, "non-null metaData indexmap");
  1004. int[] indexMap = new int[_metaData.Length];
  1005. for (int i = 0; i < indexMap.Length; ++i) {
  1006. indexMap[i] = _metaData.visibleColumns;
  1007. if (!(_metaData[i].isHidden)) {
  1008. _metaData.visibleColumns++;
  1009. }
  1010. }
  1011. _metaData.indexMap = indexMap;
  1012. }
  1013. return true;
  1014. }
  1015. override public string GetDataTypeName(int i) {
  1016. SqlStatistics statistics = null;
  1017. try {
  1018. statistics = SqlStatistics.StartTimer(Statistics);
  1019. CheckMetaDataIsReady(columnIndex: i);
  1020. return GetDataTypeNameInternal(_metaData[i]);
  1021. }
  1022. finally {
  1023. SqlStatistics.StopTimer(statistics);
  1024. }
  1025. }
  1026. private string GetDataTypeNameInternal(_SqlMetaData metaData) {
  1027. string dataTypeName = null;
  1028. if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType) {
  1029. dataTypeName = MetaType.MetaNVarChar.TypeName;
  1030. }
  1031. else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsLargeUdt) {
  1032. if (_typeSystem == SqlConnectionString.TypeSystem.SQLServer2005) {
  1033. dataTypeName = MetaType.MetaMaxVarBinary.TypeName;
  1034. }
  1035. else {
  1036. // TypeSystem.SQLServer2000
  1037. dataTypeName = MetaType.MetaImage.TypeName;
  1038. }
  1039. }
  1040. else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000) {
  1041. // TypeSystem.SQLServer2005 and above
  1042. if (metaData.type == SqlDbType.Udt) {
  1043. Debug.Assert(Connection.IsYukonOrNewer, "Invalid Column type received from the server");
  1044. dataTypeName = metaData.udtDatabaseName + "." + metaData.udtSchemaName + "." + metaData.udtTypeName;
  1045. }
  1046. else { // For all other types, including Xml - use data in MetaType.
  1047. if (metaData.cipherMD != null) {
  1048. Debug.Assert(metaData.baseTI != null && metaData.baseTI.metaType != null, "metaData.baseTI and metaData.baseTI.metaType should not be null.");
  1049. dataTypeName = metaData.baseTI.metaType.TypeName;
  1050. }
  1051. else {
  1052. dataTypeName = metaData.metaType.TypeName;
  1053. }
  1054. }
  1055. }
  1056. else {
  1057. // TypeSystem.SQLServer2000
  1058. dataTypeName = GetVersionedMetaType(metaData.metaType).TypeName;
  1059. }
  1060. return dataTypeName;
  1061. }
  1062. virtual internal SqlBuffer.StorageType GetVariantInternalStorageType(int i) {
  1063. Debug.Assert(null != _data, "Attempting to get variant internal storage type");
  1064. Debug.Assert(i < _data.Length, "Reading beyond data length?");
  1065. return _data[i].VariantInternalStorageType;
  1066. }
  1067. override public IEnumerator GetEnumerator() {
  1068. return new DbEnumerator(this, IsCommandBehavior(CommandBehavior.CloseConnection));
  1069. }
  1070. override public Type GetFieldType(int i) {
  1071. SqlStatistics statistics = null;
  1072. try {
  1073. statistics = SqlStatistics.StartTimer(Statistics);
  1074. CheckMetaDataIsReady(columnIndex: i);
  1075. return GetFieldTypeInternal(_metaData[i]);
  1076. }
  1077. finally {
  1078. SqlStatistics.StopTimer(statistics);
  1079. }
  1080. }
  1081. private Type GetFieldTypeInternal(_SqlMetaData metaData) {
  1082. Type fieldType = null;
  1083. if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType) {
  1084. // Return katmai types as string
  1085. fieldType = MetaType.MetaNVarChar.ClassType;
  1086. }
  1087. else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsLargeUdt) {
  1088. if (_typeSystem == SqlConnectionString.TypeSystem.SQLServer2005) {
  1089. fieldType = MetaType.MetaMaxVarBinary.ClassType;
  1090. }
  1091. else {
  1092. // TypeSystem.SQLServer2000
  1093. fieldType = MetaType.MetaImage.ClassType;
  1094. }
  1095. }
  1096. else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000) {
  1097. // TypeSystem.SQLServer2005 and above
  1098. if (metaData.type == SqlDbType.Udt) {
  1099. Debug.Assert(Connection.IsYukonOrNewer, "Invalid Column type received from the server");
  1100. Connection.CheckGetExtendedUDTInfo(metaData, false);
  1101. fieldType = metaData.udtType;
  1102. }
  1103. else { // For all other types, including Xml - use data in MetaType.
  1104. if (metaData.cipherMD != null) {
  1105. Debug.Assert(metaData.baseTI != null && metaData.baseTI.metaType != null, "metaData.baseTI and metaData.baseTI.metaType should not be null.");
  1106. fieldType = metaData.baseTI.metaType.ClassType;
  1107. }
  1108. else {
  1109. fieldType = metaData.metaType.ClassType; // Com+ type.
  1110. }
  1111. }
  1112. }
  1113. else {
  1114. // TypeSystem.SQLServer2000
  1115. fieldType = GetVersionedMetaType(metaData.metaType).ClassType; // Com+ type.
  1116. }
  1117. return fieldType;
  1118. }
  1119. virtual internal int GetLocaleId(int i) {
  1120. _SqlMetaData sqlMetaData = MetaData[i];
  1121. int lcid;
  1122. if (sqlMetaData.cipherMD != null) {
  1123. // If this column is encrypted, get the collation from baseTI
  1124. //
  1125. if (sqlMetaData.baseTI.collation != null) {
  1126. lcid = sqlMetaData.baseTI.collation.LCID;
  1127. }
  1128. else {
  1129. lcid = 0;
  1130. }
  1131. }
  1132. else {
  1133. if (sqlMetaData.collation != null) {
  1134. lcid = sqlMetaData.collation.LCID;
  1135. }
  1136. else {
  1137. lcid = 0;
  1138. }
  1139. }
  1140. return lcid;
  1141. }
  1142. override public string GetName(int i) {
  1143. CheckMetaDataIsReady(columnIndex: i);
  1144. Debug.Assert(null != _metaData[i].column, "MDAC 66681");
  1145. return _metaData[i].column;
  1146. }
  1147. override public Type GetProviderSpecificFieldType(int i) {
  1148. SqlStatistics statistics = null;
  1149. try {
  1150. statistics = SqlStatistics.StartTimer(Statistics);
  1151. CheckMetaDataIsReady(columnIndex: i);
  1152. return GetProviderSpecificFieldTypeInternal(_metaData[i]);
  1153. }
  1154. finally {
  1155. SqlStatistics.StopTimer(statistics);
  1156. }
  1157. }
  1158. private Type GetProviderSpecificFieldTypeInternal(_SqlMetaData metaData) {
  1159. Type providerSpecificFieldType = null;
  1160. if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType) {
  1161. providerSpecificFieldType = MetaType.MetaNVarChar.SqlType;
  1162. }
  1163. else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsLargeUdt) {
  1164. if (_typeSystem == SqlConnectionString.TypeSystem.SQLServer2005) {
  1165. providerSpecificFieldType = MetaType.MetaMaxVarBinary.SqlType;
  1166. }
  1167. else {
  1168. // TypeSystem.SQLServer2000
  1169. providerSpecificFieldType = MetaType.MetaImage.SqlType;
  1170. }
  1171. }
  1172. else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000) {
  1173. // TypeSystem.SQLServer2005 and above
  1174. if (metaData.type == SqlDbType.Udt) {
  1175. Debug.Assert(Connection.IsYukonOrNewer, "Invalid Column type received from the server");
  1176. Connection.CheckGetExtendedUDTInfo(metaData, false);
  1177. providerSpecificFieldType = metaData.udtType;
  1178. }
  1179. else {
  1180. // For all other types, including Xml - use data in MetaType.
  1181. if (metaData.cipherMD != null) {
  1182. Debug.Assert(metaData.baseTI != null && metaData.baseTI.metaType != null,
  1183. "metaData.baseTI and metaData.baseTI.metaType should not be null.");
  1184. providerSpecificFieldType = metaData.baseTI.metaType.SqlType; // SqlType type.
  1185. }
  1186. else {
  1187. providerSpecificFieldType = metaData.metaType.SqlType; // SqlType type.
  1188. }
  1189. }
  1190. }
  1191. else {
  1192. // TypeSystem.SQLServer2000
  1193. providerSpecificFieldType = GetVersionedMetaType(metaData.metaType).SqlType; // SqlType type.
  1194. }
  1195. return providerSpecificFieldType;
  1196. }
  1197. // named field access
  1198. override public int GetOrdinal(string name) {
  1199. SqlStatistics statistics = null;
  1200. try {
  1201. statistics = SqlStatistics.StartTimer(Statistics);
  1202. if (null == _fieldNameLookup) {
  1203. CheckMetaDataIsReady();
  1204. _fieldNameLookup = new FieldNameLookup(this, _defaultLCID);
  1205. }
  1206. return _fieldNameLookup.GetOrdinal(name); // MDAC 71470
  1207. }
  1208. finally {
  1209. SqlStatistics.StopTimer(statistics);
  1210. }
  1211. }
  1212. override public object GetProviderSpecificValue(int i) {
  1213. return GetSqlValue(i);
  1214. }
  1215. override public int GetProviderSpecificValues(object[] values) {
  1216. return GetSqlValues(values);
  1217. }
  1218. override public DataTable GetSchemaTable() {
  1219. SqlStatistics statistics = null;
  1220. IntPtr hscp;
  1221. Bid.ScopeEnter(out hscp, "<sc.SqlDataReader.GetSchemaTable|API> %d#", ObjectID);
  1222. try {
  1223. statistics = SqlStatistics.StartTimer(Statistics);
  1224. if (null == _metaData || null == _metaData.schemaTable) {
  1225. if (null != this.MetaData) {
  1226. _metaData.schemaTable = BuildSchemaTable();
  1227. Debug.Assert(null != _metaData.schemaTable, "No schema information yet!");
  1228. // filter table?
  1229. }
  1230. }
  1231. if (null != _metaData) {
  1232. return _metaData.schemaTable;
  1233. }
  1234. return null;
  1235. }
  1236. finally {
  1237. SqlStatistics.StopTimer(statistics);
  1238. Bid.ScopeLeave(ref hscp);
  1239. }
  1240. }
  1241. override public bool GetBoolean(int i) {
  1242. ReadColumn(i);
  1243. return _data[i].Boolean;
  1244. }
  1245. virtual public XmlReader GetXmlReader(int i) {
  1246. // NOTE: sql_variant can not contain a XML data type: http://msdn.microsoft.com/en-us/library/ms173829.aspx
  1247. // If this ever changes, the following code should be changed to be like GetStream\GetTextReader
  1248. CheckDataIsReady(columnIndex: i, methodName: "GetXmlReader");
  1249. MetaType mt = _metaData[i].metaType;
  1250. // XmlReader only allowed on XML types
  1251. if (mt.SqlDbType != SqlDbType.Xml) {
  1252. throw SQL.XmlReaderNotSupportOnColumnType(_metaData[i].column);
  1253. }
  1254. if (IsCommandBehavior(CommandBehavior.SequentialAccess)) {
  1255. // Wrap the sequential stream in an XmlReader
  1256. _currentStream = new SqlSequentialStream(this, i);
  1257. _lastColumnWithDataChunkRead = i;
  1258. return SqlXml.CreateSqlXmlReader(_currentStream, closeInput: true);
  1259. }
  1260. else {
  1261. // Need to call ReadColumn, since we want to access the internal data structures (i.e. SqlBinary) rather than calling anther Get*() method
  1262. ReadColumn(i);
  1263. if (_data[i].IsNull) {
  1264. // A 'null' stream
  1265. return SqlXml.CreateSqlXmlReader(new MemoryStream(new byte[0], writable: false), closeInput: true);
  1266. }
  1267. else {
  1268. // Grab already read data
  1269. return _data[i].SqlXml.CreateReader();
  1270. }
  1271. }
  1272. }
  1273. override public Stream GetStream(int i) {
  1274. CheckDataIsReady(columnIndex: i, methodName: "GetStream");
  1275. // Streaming is not supported on encrypted columns.
  1276. if (_metaData[i] != null && _metaData[i].cipherMD != null) {
  1277. throw SQL.StreamNotSupportOnEncryptedColumn(_metaData[i].column);
  1278. }
  1279. // Stream is only for Binary, Image, VarBinary, Udt and Xml types
  1280. // NOTE: IsBinType also includes Timestamp for some reason...
  1281. MetaType mt = _metaData[i].metaType;
  1282. if (((!mt.IsBinType) || (mt.SqlDbType == SqlDbType.Timestamp)) && (mt.SqlDbType != SqlDbType.Variant)) {
  1283. throw SQL.StreamNotSupportOnColumnType(_metaData[i].column);
  1284. }
  1285. // For non-variant types with sequential access, we support proper streaming
  1286. if ((mt.SqlDbType != SqlDbType.Variant) && (IsCommandBehavior(CommandBehavior.SequentialAccess))) {
  1287. _currentStream = new SqlSequentialStream(this, i);
  1288. _lastColumnWithDataChunkRead = i;
  1289. return _currentStream;
  1290. }
  1291. else {
  1292. // Need to call ReadColumn, since we want to access the internal data structures (i.e. SqlBinary) rather than calling anther Get*() method
  1293. ReadColumn(i);
  1294. byte[] data;
  1295. if (_data[i].IsNull) {
  1296. // A 'null' stream
  1297. data = new byte[0];
  1298. }
  1299. else {
  1300. // Grab already read data
  1301. data = _data[i].SqlBinary.Value;
  1302. }
  1303. // If non-sequential then we just have a read-only MemoryStream
  1304. return new MemoryStream(data, writable: false);
  1305. }
  1306. }
  1307. override public byte GetByte(int i) {
  1308. ReadColumn(i);
  1309. return _data[i].Byte;
  1310. }
  1311. override public long GetBytes(int i, long dataIndex, byte[] buffer, int bufferIndex, int length) {
  1312. SqlStatistics statistics = null;
  1313. long cbBytes = 0;
  1314. CheckDataIsReady(columnIndex: i, allowPartiallyReadColumn: true, methodName: "GetBytes");
  1315. // don't allow get bytes on non-long or non-binary columns
  1316. MetaType mt = _metaData[i].metaType;
  1317. if (!(mt.IsLong || mt.IsBinType) || (SqlDbType.Xml == mt.SqlDbType)) {
  1318. throw SQL.NonBlobColumn(_metaData[i].column);
  1319. }
  1320. try {
  1321. statistics = SqlStatistics.StartTimer(Statistics);
  1322. SetTimeout(_defaultTimeoutMilliseconds);
  1323. cbBytes = GetBytesInternal(i, dataIndex, buffer, bufferIndex, length);
  1324. _lastColumnWithDataChunkRead = i;
  1325. }
  1326. finally {
  1327. SqlStatistics.StopTimer(statistics);
  1328. }
  1329. return cbBytes;
  1330. }
  1331. // Used (indirectly) by SqlCommand.CompleteXmlReader
  1332. virtual internal long GetBytesInternal(int i, long dataIndex, byte[] buffer, int bufferIndex, int length) {
  1333. if (_currentTask != null) {
  1334. throw ADP.AsyncOperationPending();
  1335. }
  1336. long value;
  1337. Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  1338. bool result = TryGetBytesInternal(i, dataIndex, buffer, bufferIndex, length, out value);
  1339. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  1340. return value;
  1341. }
  1342. private bool TryGetBytesInternal(int i, long dataIndex, byte[] buffer, int bufferIndex, int length, out long remaining) {
  1343. remaining = 0;
  1344. RuntimeHelpers.PrepareConstrainedRegions();
  1345. try {
  1346. #if DEBUG
  1347. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  1348. RuntimeHelpers.PrepareConstrainedRegions();
  1349. try {
  1350. tdsReliabilitySection.Start();
  1351. #else
  1352. {
  1353. #endif //DEBUG
  1354. int cbytes = 0;
  1355. AssertReaderState(requireData: true, permitAsync: true, columnIndex: i, enforceSequentialAccess: true);
  1356. // sequential reading
  1357. if (IsCommandBehavior(CommandBehavior.SequentialAccess)) {
  1358. Debug.Assert(!HasActiveStreamOrTextReaderOnColumn(i), "Column has an active Stream or TextReader");
  1359. if (_metaData[i] != null && _metaData[i].cipherMD != null) {
  1360. throw SQL.SequentialAccessNotSupportedOnEncryptedColumn(_metaData[i].column);
  1361. }
  1362. if (_sharedState._nextColumnHeaderToRead <= i) {
  1363. if (!TryReadColumnHeader(i)) {
  1364. return false;
  1365. }
  1366. }
  1367. // If data is null, ReadColumnHeader sets the data.IsNull bit.
  1368. if (_data[i] != null && _data[i].IsNull) {
  1369. throw new SqlNullValueException();
  1370. }
  1371. // If there are an unknown (-1) number of bytes left for a PLP, read its size
  1372. if ((-1 == _sharedState._columnDataBytesRemaining) && (_metaData[i].metaType.IsPlp)) {
  1373. ulong left;
  1374. if (!_parser.TryPlpBytesLeft(_stateObj, out left)) {
  1375. return false;
  1376. }
  1377. _sharedState._columnDataBytesRemaining = (long)left;
  1378. }
  1379. if (0 == _sharedState._columnDataBytesRemaining) {
  1380. return true; // We've read this column to the end
  1381. }
  1382. // if no buffer is passed in, return the number total of bytes, or -1
  1383. if (null == buffer) {
  1384. if (_metaData[i].metaType.IsPlp) {
  1385. remaining = (long) _parser.PlpBytesTotalLength(_stateObj);
  1386. return true;
  1387. }
  1388. remaining = _sharedState._columnDataBytesRemaining;
  1389. return true;
  1390. }
  1391. if (dataIndex < 0)
  1392. throw ADP.NegativeParameter("dataIndex");
  1393. if (dataIndex < _columnDataBytesRead) {
  1394. throw ADP.NonSeqByteAccess(dataIndex, _columnDataBytesRead, ADP.GetBytes);
  1395. }
  1396. // if the dataIndex is not equal to bytes read, then we have to skip bytes
  1397. long cb = dataIndex - _columnDataBytesRead;
  1398. // if dataIndex is outside of the data range, return 0
  1399. if ((cb > _sharedState._columnDataBytesRemaining) && !_metaData[i].metaType.IsPlp) {
  1400. return true;
  1401. }
  1402. // if bad buffer index, throw
  1403. if (bufferIndex < 0 || bufferIndex >= buffer.Length)
  1404. throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, "bufferIndex");
  1405. // if there is not enough room in the buffer for data
  1406. if (length + bufferIndex > buffer.Length)
  1407. throw ADP.InvalidBufferSizeOrIndex(length, bufferIndex);
  1408. if (length < 0)
  1409. throw ADP.InvalidDataLength(length);
  1410. // Skip if needed
  1411. if (cb > 0) {
  1412. if (_metaData[i].metaType.IsPlp) {
  1413. ulong skipped;
  1414. if (!_parser.TrySkipPlpValue((ulong) cb, _stateObj, out skipped)) {
  1415. return false;
  1416. }
  1417. _columnDataBytesRead += (long) skipped;
  1418. }
  1419. else {
  1420. if (!_stateObj.TrySkipLongBytes(cb)) {
  1421. return false;
  1422. }
  1423. _columnDataBytesRead += cb;
  1424. _sharedState._columnDataBytesRemaining -= cb;
  1425. }
  1426. }
  1427. int bytesRead;
  1428. bool result = TryGetBytesInternalSequential(i, buffer, bufferIndex, length, out bytesRead);
  1429. remaining = (int)bytesRead;
  1430. return result;
  1431. }
  1432. // random access now!
  1433. // note that since we are caching in an array, and arrays aren't 64 bit ready yet,
  1434. // we need can cast to int if the dataIndex is in range
  1435. if (dataIndex < 0)
  1436. throw ADP.NegativeParameter("dataIndex");
  1437. if (dataIndex > Int32.MaxValue) {
  1438. throw ADP.InvalidSourceBufferIndex(cbytes, dataIndex, "dataIndex");
  1439. }
  1440. int ndataIndex = (int)dataIndex;
  1441. byte[] data;
  1442. // WebData 99342 - in the non-sequential case, we need to support
  1443. // the use of GetBytes on string data columns, but
  1444. // GetSqlBinary isn't supposed to. What we end up
  1445. // doing isn't exactly pretty, but it does work.
  1446. if (_metaData[i].metaType.IsBinType) {
  1447. data = GetSqlBinary(i).Value;
  1448. }
  1449. else {
  1450. Debug.Assert(_metaData[i].metaType.IsLong, "non long type?");
  1451. Debug.Assert(_metaData[i].metaType.IsCharType, "non-char type?");
  1452. SqlString temp = GetSqlString(i);
  1453. if (_metaData[i].metaType.IsNCharType) {
  1454. data = temp.GetUnicodeBytes();
  1455. }
  1456. else {
  1457. data = temp.GetNonUnicodeBytes();
  1458. }
  1459. }
  1460. cbytes = data.Length;
  1461. // if no buffer is passed in, return the number of characters we have
  1462. if (null == buffer) {
  1463. remaining = cbytes;
  1464. return true;
  1465. }
  1466. // if dataIndex is outside of data range, return 0
  1467. if (ndataIndex < 0 || ndataIndex >= cbytes) {
  1468. return true;
  1469. }
  1470. try {
  1471. if (ndataIndex < cbytes) {
  1472. // help the user out in the case where there's less data than requested
  1473. if ((ndataIndex + length) > cbytes)
  1474. cbytes = cbytes - ndataIndex;
  1475. else
  1476. cbytes = length;
  1477. }
  1478. Array.Copy(data, ndataIndex, buffer, bufferIndex, cbytes);
  1479. }
  1480. catch (Exception e) {
  1481. //
  1482. if (!ADP.IsCatchableExceptionType(e)) {
  1483. throw;
  1484. }
  1485. cbytes = data.Length;
  1486. if (length < 0)
  1487. throw ADP.InvalidDataLength(length);
  1488. // if bad buffer index, throw
  1489. if (bufferIndex < 0 || bufferIndex >= buffer.Length)
  1490. throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, "bufferIndex");
  1491. // if there is not enough room in the buffer for data
  1492. if (cbytes + bufferIndex > buffer.Length)
  1493. throw ADP.InvalidBufferSizeOrIndex(cbytes, bufferIndex);
  1494. throw;
  1495. }
  1496. remaining = cbytes;
  1497. return true;
  1498. }
  1499. #if DEBUG
  1500. finally {
  1501. tdsReliabilitySection.Stop();
  1502. }
  1503. #endif //DEBUG
  1504. }
  1505. catch (System.OutOfMemoryException e) {
  1506. _isClosed = true;
  1507. if (null != _connection) {
  1508. _connection.Abort(e);
  1509. }
  1510. throw;
  1511. }
  1512. catch (System.StackOverflowException e) {
  1513. _isClosed = true;
  1514. if (null != _connection) {
  1515. _connection.Abort(e);
  1516. }
  1517. throw;
  1518. }
  1519. catch (System.Threading.ThreadAbortException e) {
  1520. _isClosed = true;
  1521. if (null != _connection) {
  1522. _connection.Abort(e);
  1523. }
  1524. throw;
  1525. }
  1526. }
  1527. internal int GetBytesInternalSequential(int i, byte[] buffer, int index, int length, long? timeoutMilliseconds = null) {
  1528. if (_currentTask != null) {
  1529. throw ADP.AsyncOperationPending();
  1530. }
  1531. int value;
  1532. SqlStatistics statistics = null;
  1533. Debug.Assert(_stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  1534. try {
  1535. statistics = SqlStatistics.StartTimer(Statistics);
  1536. SetTimeout(timeoutMilliseconds ?? _defaultTimeoutMilliseconds);
  1537. bool result = TryReadColumnHeader(i);
  1538. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  1539. result = TryGetBytesInternalSequential(i, buffer, index, length, out value);
  1540. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  1541. }
  1542. finally {
  1543. SqlStatistics.StopTimer(statistics);
  1544. }
  1545. return value;
  1546. }
  1547. // This is meant to be called from other internal methods once we are at the column to read
  1548. // NOTE: This method must be retriable WITHOUT replaying a snapshot
  1549. // Every time you call this method increment the index and decrease length by the value of bytesRead
  1550. internal bool TryGetBytesInternalSequential(int i, byte[] buffer, int index, int length, out int bytesRead) {
  1551. AssertReaderState(requireData: true, permitAsync: true, columnIndex: i, enforceSequentialAccess: true);
  1552. Debug.Assert(_sharedState._nextColumnHeaderToRead == i + 1 && _sharedState._nextColumnDataToRead == i, "Non sequential access");
  1553. Debug.Assert(buffer != null, "Null buffer");
  1554. Debug.Assert(index >= 0, "Invalid index");
  1555. Debug.Assert(length >= 0, "Invalid length");
  1556. Debug.Assert(index + length <= buffer.Length, "Buffer too small");
  1557. bytesRead = 0;
  1558. RuntimeHelpers.PrepareConstrainedRegions();
  1559. try
  1560. {
  1561. #if DEBUG
  1562. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  1563. RuntimeHelpers.PrepareConstrainedRegions();
  1564. try {
  1565. tdsReliabilitySection.Start();
  1566. #endif //DEBUG
  1567. if ((_sharedState._columnDataBytesRemaining == 0) || (length == 0)) {
  1568. // No data left or nothing requested, return 0
  1569. bytesRead = 0;
  1570. return true;
  1571. }
  1572. else {
  1573. // if plp columns, do partial reads. Don't read the entire value in one shot.
  1574. if (_metaData[i].metaType.IsPlp) {
  1575. // Read in data
  1576. bool result = _stateObj.TryReadPlpBytes(ref buffer, index, length, out bytesRead);
  1577. _columnDataBytesRead += bytesRead;
  1578. if (!result) {
  1579. return false;
  1580. }
  1581. // Query for number of bytes left
  1582. ulong left;
  1583. if (!_parser.TryPlpBytesLeft(_stateObj, out left)) {
  1584. _sharedState._columnDataBytesRemaining = -1;
  1585. return false;
  1586. }
  1587. _sharedState._columnDataBytesRemaining = (long)left;
  1588. return true;
  1589. }
  1590. else {
  1591. // Read data (not exceeding the total amount of data available)
  1592. int bytesToRead = (int)Math.Min((long)length, _sharedState._columnDataBytesRemaining);
  1593. bool result = _stateObj.TryReadByteArray(buffer, index, bytesToRead, out bytesRead);
  1594. _columnDataBytesRead += bytesRead;
  1595. _sharedState._columnDataBytesRemaining -= bytesRead;
  1596. return result;
  1597. }
  1598. }
  1599. #if DEBUG
  1600. }
  1601. finally {
  1602. tdsReliabilitySection.Stop();
  1603. }
  1604. #endif //DEBUG
  1605. }
  1606. catch (System.OutOfMemoryException e) {
  1607. _isClosed = true;
  1608. if (null != _connection) {
  1609. _connection.Abort(e);
  1610. }
  1611. throw;
  1612. }
  1613. catch (System.StackOverflowException e) {
  1614. _isClosed = true;
  1615. if (null != _connection) {
  1616. _connection.Abort(e);
  1617. }
  1618. throw;
  1619. }
  1620. catch (System.Threading.ThreadAbortException e) {
  1621. _isClosed = true;
  1622. if (null != _connection) {
  1623. _connection.Abort(e);
  1624. }
  1625. throw;
  1626. }
  1627. }
  1628. override public TextReader GetTextReader(int i) {
  1629. CheckDataIsReady(columnIndex: i, methodName: "GetTextReader");
  1630. // Xml type is not supported
  1631. MetaType mt = null;
  1632. if (_metaData[i].cipherMD != null) {
  1633. Debug.Assert(_metaData[i].baseTI != null, "_metaData[i].baseTI should not be null.");
  1634. mt = _metaData[i].baseTI.metaType;
  1635. }
  1636. else {
  1637. mt = _metaData[i].metaType;
  1638. }
  1639. Debug.Assert(mt != null, @"mt should not be null.");
  1640. if (((!mt.IsCharType) && (mt.SqlDbType != SqlDbType.Variant)) || (mt.SqlDbType == SqlDbType.Xml)) {
  1641. throw SQL.TextReaderNotSupportOnColumnType(_metaData[i].column);
  1642. }
  1643. // For non-variant types with sequential access, we support proper streaming
  1644. if ((mt.SqlDbType != SqlDbType.Variant) && (IsCommandBehavior(CommandBehavior.SequentialAccess))) {
  1645. if (_metaData[i].cipherMD != null) {
  1646. throw SQL.SequentialAccessNotSupportedOnEncryptedColumn(_metaData[i].column);
  1647. }
  1648. System.Text.Encoding encoding;
  1649. if (mt.IsNCharType)
  1650. {
  1651. // NChar types always use unicode
  1652. encoding = SqlUnicodeEncoding.SqlUnicodeEncodingInstance;
  1653. }
  1654. else
  1655. {
  1656. encoding = _metaData[i].encoding;
  1657. }
  1658. _currentTextReader = new SqlSequentialTextReader(this, i, encoding);
  1659. _lastColumnWithDataChunkRead = i;
  1660. return _currentTextReader;
  1661. }
  1662. else {
  1663. // Need to call ReadColumn, since we want to access the internal data structures (i.e. SqlString) rather than calling anther Get*() method
  1664. ReadColumn(i);
  1665. string data;
  1666. if (_data[i].IsNull) {
  1667. // A 'null' stream
  1668. data = string.Empty;
  1669. }
  1670. else {
  1671. // Grab already read data
  1672. data = _data[i].SqlString.Value;
  1673. }
  1674. // We've already read the data, so just wrap it in a StringReader
  1675. return new StringReader(data);
  1676. }
  1677. }
  1678. [ EditorBrowsableAttribute(EditorBrowsableState.Never) ] // MDAC 69508
  1679. override public char GetChar(int i) {
  1680. throw ADP.NotSupported();
  1681. }
  1682. override public long GetChars(int i, long dataIndex, char[] buffer, int bufferIndex, int length) {
  1683. SqlStatistics statistics = null;
  1684. CheckMetaDataIsReady(columnIndex: i);
  1685. if (_currentTask != null) {
  1686. throw ADP.AsyncOperationPending();
  1687. }
  1688. MetaType mt = null;
  1689. if (_metaData[i].cipherMD != null) {
  1690. Debug.Assert(_metaData[i].baseTI != null, @"_metaData[i].baseTI should not be null.");
  1691. mt = _metaData[i].baseTI.metaType;
  1692. }
  1693. else {
  1694. mt = _metaData[i].metaType;
  1695. }
  1696. Debug.Assert(mt != null, "mt should not be null.");
  1697. SqlDbType sqlDbType;
  1698. if (_metaData[i].cipherMD != null) {
  1699. Debug.Assert(_metaData[i].baseTI != null, @"_metaData[i].baseTI should not be null.");
  1700. sqlDbType = _metaData[i].baseTI.type;
  1701. }
  1702. else {
  1703. sqlDbType = _metaData[i].type;
  1704. }
  1705. try {
  1706. statistics = SqlStatistics.StartTimer(Statistics);
  1707. SetTimeout(_defaultTimeoutMilliseconds);
  1708. if ((mt.IsPlp) &&
  1709. (IsCommandBehavior(CommandBehavior.SequentialAccess)) ) {
  1710. if (length < 0) {
  1711. throw ADP.InvalidDataLength(length);
  1712. }
  1713. if (_metaData[i].cipherMD != null) {
  1714. throw SQL.SequentialAccessNotSupportedOnEncryptedColumn(_metaData[i].column);
  1715. }
  1716. // if bad buffer index, throw
  1717. if ((bufferIndex < 0) || (buffer != null && bufferIndex >= buffer.Length)) {
  1718. throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, "bufferIndex");
  1719. }
  1720. // if there is not enough room in the buffer for data
  1721. if (buffer != null && (length + bufferIndex > buffer.Length)) {
  1722. throw ADP.InvalidBufferSizeOrIndex(length, bufferIndex);
  1723. }
  1724. long charsRead = 0;
  1725. if ( sqlDbType == SqlDbType.Xml ) {
  1726. try {
  1727. CheckDataIsReady(columnIndex: i, allowPartiallyReadColumn: true, methodName: "GetChars");
  1728. }
  1729. catch (Exception ex) {
  1730. // Dev11 Bug #315513: Exception type breaking change from 4.0 RTM when calling GetChars on null xml
  1731. // We need to wrap all exceptions inside a TargetInvocationException to simulate calling CreateSqlReader via MethodInfo.Invoke
  1732. if (ADP.IsCatchableExceptionType(ex)) {
  1733. throw new TargetInvocationException(ex);
  1734. }
  1735. else {
  1736. throw;
  1737. }
  1738. }
  1739. charsRead = GetStreamingXmlChars(i, dataIndex, buffer, bufferIndex, length);
  1740. }
  1741. else {
  1742. CheckDataIsReady(columnIndex: i, allowPartiallyReadColumn: true, methodName: "GetChars");
  1743. charsRead = GetCharsFromPlpData(i, dataIndex, buffer, bufferIndex, length);
  1744. }
  1745. _lastColumnWithDataChunkRead = i;
  1746. return charsRead;
  1747. }
  1748. // Did we start reading this value yet?
  1749. if ((_sharedState._nextColumnDataToRead == (i+1)) && (_sharedState._nextColumnHeaderToRead == (i+1)) && (_columnDataChars != null) && (IsCommandBehavior(CommandBehavior.SequentialAccess)) && (dataIndex < _columnDataCharsRead)) {
  1750. // Don't allow re-read of same chars in sequential access mode
  1751. throw ADP.NonSeqByteAccess(dataIndex, _columnDataCharsRead, ADP.GetChars);
  1752. }
  1753. if (_columnDataCharsIndex != i) {
  1754. // if the object doesn't contain a char[] then the user will get an exception
  1755. string s = GetSqlString(i).Value;
  1756. _columnDataChars = s.ToCharArray();
  1757. _columnDataCharsRead = 0;
  1758. _columnDataCharsIndex = i;
  1759. }
  1760. int cchars = _columnDataChars.Length;
  1761. // note that since we are caching in an array, and arrays aren't 64 bit ready yet,
  1762. // we need can cast to int if the dataIndex is in range
  1763. if (dataIndex > Int32.MaxValue) {
  1764. throw ADP.InvalidSourceBufferIndex(cchars, dataIndex, "dataIndex");
  1765. }
  1766. int ndataIndex = (int)dataIndex;
  1767. // if no buffer is passed in, return the number of characters we have
  1768. if (null == buffer)
  1769. return cchars;
  1770. // if dataIndex outside of data range, return 0
  1771. if (ndataIndex < 0 || ndataIndex >= cchars)
  1772. return 0;
  1773. try {
  1774. if (ndataIndex < cchars) {
  1775. // help the user out in the case where there's less data than requested
  1776. if ((ndataIndex + length) > cchars)
  1777. cchars = cchars - ndataIndex;
  1778. else
  1779. cchars = length;
  1780. }
  1781. Array.Copy(_columnDataChars, ndataIndex, buffer, bufferIndex, cchars);
  1782. _columnDataCharsRead += cchars;
  1783. }
  1784. catch (Exception e) {
  1785. //
  1786. if (!ADP.IsCatchableExceptionType(e)) {
  1787. throw;
  1788. }
  1789. cchars = _columnDataChars.Length;
  1790. if (length < 0)
  1791. throw ADP.InvalidDataLength(length);
  1792. // if bad buffer index, throw
  1793. if (bufferIndex < 0 || bufferIndex >= buffer.Length)
  1794. throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, "bufferIndex");
  1795. // if there is not enough room in the buffer for data
  1796. if (cchars + bufferIndex > buffer.Length)
  1797. throw ADP.InvalidBufferSizeOrIndex(cchars, bufferIndex);
  1798. throw;
  1799. }
  1800. return cchars;
  1801. }
  1802. finally {
  1803. SqlStatistics.StopTimer(statistics);
  1804. }
  1805. }
  1806. private long GetCharsFromPlpData(int i, long dataIndex, char[] buffer, int bufferIndex, int length) {
  1807. RuntimeHelpers.PrepareConstrainedRegions();
  1808. try {
  1809. #if DEBUG
  1810. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  1811. RuntimeHelpers.PrepareConstrainedRegions();
  1812. try {
  1813. tdsReliabilitySection.Start();
  1814. #else
  1815. {
  1816. #endif //DEBUG
  1817. long cch;
  1818. AssertReaderState(requireData: true, permitAsync: false, columnIndex: i, enforceSequentialAccess: true);
  1819. Debug.Assert(!HasActiveStreamOrTextReaderOnColumn(i), "Column has active Stream or TextReader");
  1820. // don't allow get bytes on non-long or non-binary columns
  1821. Debug.Assert(_metaData[i].metaType.IsPlp, "GetCharsFromPlpData called on a non-plp column!");
  1822. // Must be sequential reading
  1823. Debug.Assert (IsCommandBehavior(CommandBehavior.SequentialAccess), "GetCharsFromPlpData called for non-Sequential access");
  1824. if (!_metaData[i].metaType.IsCharType) {
  1825. throw SQL.NonCharColumn(_metaData[i].column);
  1826. }
  1827. if (_sharedState._nextColumnHeaderToRead <= i) {
  1828. ReadColumnHeader(i);
  1829. }
  1830. // If data is null, ReadColumnHeader sets the data.IsNull bit.
  1831. if (_data[i] != null && _data[i].IsNull) {
  1832. throw new SqlNullValueException();
  1833. }
  1834. if (dataIndex < _columnDataCharsRead) {
  1835. // Don't allow re-read of same chars in sequential access mode
  1836. throw ADP.NonSeqByteAccess(dataIndex, _columnDataCharsRead, ADP.GetChars);
  1837. }
  1838. // If we start reading the new column, either dataIndex is 0 or
  1839. // _columnDataCharsRead is 0 and dataIndex > _columnDataCharsRead is true below.
  1840. // In both cases we will clean decoder
  1841. if (dataIndex == 0)
  1842. _stateObj._plpdecoder = null;
  1843. bool isUnicode = _metaData[i].metaType.IsNCharType;
  1844. // If there are an unknown (-1) number of bytes left for a PLP, read its size
  1845. if (-1 == _sharedState._columnDataBytesRemaining) {
  1846. _sharedState._columnDataBytesRemaining = (long)_parser.PlpBytesLeft(_stateObj);
  1847. }
  1848. if (0 == _sharedState._columnDataBytesRemaining) {
  1849. _stateObj._plpdecoder = null;
  1850. return 0; // We've read this column to the end
  1851. }
  1852. // if no buffer is passed in, return the total number of characters or -1
  1853. //
  1854. if (null == buffer) {
  1855. cch = (long) _parser.PlpBytesTotalLength(_stateObj);
  1856. return (isUnicode && (cch > 0)) ? cch >> 1 : cch;
  1857. }
  1858. if (dataIndex > _columnDataCharsRead) {
  1859. // Skip chars
  1860. // Clean decoder state: we do not reset it, but destroy to ensure
  1861. // that we do not start decoding the column with decoder from the old one
  1862. _stateObj._plpdecoder = null;
  1863. //
  1864. cch = dataIndex - _columnDataCharsRead;
  1865. cch = isUnicode ? (cch << 1 ) : cch;
  1866. cch = (long) _parser.SkipPlpValue((ulong)(cch), _stateObj);
  1867. _columnDataBytesRead += cch;
  1868. _columnDataCharsRead += (isUnicode && (cch > 0)) ? cch >> 1 : cch;
  1869. }
  1870. cch = length;
  1871. if (isUnicode) {
  1872. cch = (long) _parser.ReadPlpUnicodeChars(ref buffer, bufferIndex, length, _stateObj);
  1873. _columnDataBytesRead += (cch << 1);
  1874. }
  1875. else {
  1876. cch = (long) _parser.ReadPlpAnsiChars(ref buffer, bufferIndex, length, _metaData[i], _stateObj);
  1877. _columnDataBytesRead += cch << 1;
  1878. }
  1879. _columnDataCharsRead += cch;
  1880. _sharedState._columnDataBytesRemaining = (long)_parser.PlpBytesLeft(_stateObj);
  1881. return cch;
  1882. }
  1883. #if DEBUG
  1884. finally {
  1885. tdsReliabilitySection.Stop();
  1886. }
  1887. #endif //DEBUG
  1888. }
  1889. catch (System.OutOfMemoryException e) {
  1890. _isClosed = true;
  1891. if (null != _connection) {
  1892. _connection.Abort(e);
  1893. }
  1894. throw;
  1895. }
  1896. catch (System.StackOverflowException e) {
  1897. _isClosed = true;
  1898. if (null != _connection) {
  1899. _connection.Abort(e);
  1900. }
  1901. throw;
  1902. }
  1903. catch (System.Threading.ThreadAbortException e) {
  1904. _isClosed = true;
  1905. if (null != _connection) {
  1906. _connection.Abort(e);
  1907. }
  1908. throw;
  1909. }
  1910. }
  1911. internal long GetStreamingXmlChars(int i, long dataIndex, char[] buffer, int bufferIndex, int length) {
  1912. SqlStreamingXml localSXml = null;
  1913. if ((_streamingXml != null) && ( _streamingXml.ColumnOrdinal != i)) {
  1914. _streamingXml.Close();
  1915. _streamingXml = null;
  1916. }
  1917. if (_streamingXml == null) {
  1918. localSXml = new SqlStreamingXml(i, this);
  1919. }
  1920. else {
  1921. localSXml = _streamingXml;
  1922. }
  1923. long cnt = localSXml.GetChars(dataIndex, buffer, bufferIndex, length);
  1924. if (_streamingXml == null) {
  1925. // Data is read through GetBytesInternal which may dispose _streamingXml if it has to advance the column ordinal.
  1926. // Therefore save the new SqlStreamingXml class after the read succeeds.
  1927. _streamingXml = localSXml;
  1928. }
  1929. return cnt;
  1930. }
  1931. [ EditorBrowsableAttribute(EditorBrowsableState.Never) ] // MDAC 69508
  1932. IDataReader IDataRecord.GetData(int i) {
  1933. throw ADP.NotSupported();
  1934. }
  1935. override public DateTime GetDateTime(int i) {
  1936. ReadColumn(i);
  1937. DateTime dt = _data[i].DateTime;
  1938. // This accessor can be called for regular DateTime column. In this case we should not throw
  1939. if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && _metaData[i].IsNewKatmaiDateTimeType) {
  1940. // TypeSystem.SQLServer2005 or less
  1941. // If the above succeeds, then we received a valid DateTime instance, now we need to force
  1942. // an InvalidCastException since DateTime is not exposed with the version knob in this setting.
  1943. // To do so, we simply force the exception by casting the string representation of the value
  1944. // To DateTime.
  1945. object temp = (object) _data[i].String;
  1946. dt = (DateTime) temp;
  1947. }
  1948. return dt;
  1949. }
  1950. override public Decimal GetDecimal(int i) {
  1951. ReadColumn(i);
  1952. return _data[i].Decimal;
  1953. }
  1954. override public double GetDouble(int i) {
  1955. ReadColumn(i);
  1956. return _data[i].Double;
  1957. }
  1958. override public float GetFloat(int i) {
  1959. ReadColumn(i);
  1960. return _data[i].Single;
  1961. }
  1962. override public Guid GetGuid(int i) {
  1963. ReadColumn(i);
  1964. return _data[i].SqlGuid.Value;
  1965. }
  1966. override public Int16 GetInt16(int i) {
  1967. ReadColumn(i);
  1968. return _data[i].Int16;
  1969. }
  1970. override public Int32 GetInt32(int i) {
  1971. ReadColumn(i);
  1972. return _data[i].Int32;
  1973. }
  1974. override public Int64 GetInt64(int i) {
  1975. ReadColumn(i);
  1976. return _data[i].Int64;
  1977. }
  1978. virtual public SqlBoolean GetSqlBoolean(int i) {
  1979. ReadColumn(i);
  1980. return _data[i].SqlBoolean;
  1981. }
  1982. virtual public SqlBinary GetSqlBinary(int i) {
  1983. ReadColumn(i, setTimeout: true, allowPartiallyReadColumn: true);
  1984. return _data[i].SqlBinary;
  1985. }
  1986. virtual public SqlByte GetSqlByte(int i) {
  1987. ReadColumn(i);
  1988. return _data[i].SqlByte;
  1989. }
  1990. virtual public SqlBytes GetSqlBytes(int i) {
  1991. ReadColumn(i);
  1992. SqlBinary data = _data[i].SqlBinary;
  1993. return new SqlBytes(data);
  1994. }
  1995. virtual public SqlChars GetSqlChars(int i) {
  1996. ReadColumn(i);
  1997. SqlString data;
  1998. // Convert Katmai types to string
  1999. if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && _metaData[i].IsNewKatmaiDateTimeType)
  2000. {
  2001. data = _data[i].KatmaiDateTimeSqlString;
  2002. } else {
  2003. data = _data[i].SqlString;
  2004. }
  2005. return new SqlChars(data);
  2006. }
  2007. virtual public SqlDateTime GetSqlDateTime(int i) {
  2008. ReadColumn(i);
  2009. return _data[i].SqlDateTime;
  2010. }
  2011. virtual public SqlDecimal GetSqlDecimal(int i) {
  2012. ReadColumn(i);
  2013. return _data[i].SqlDecimal;
  2014. }
  2015. virtual public SqlGuid GetSqlGuid(int i) {
  2016. ReadColumn(i);
  2017. return _data[i].SqlGuid;
  2018. }
  2019. virtual public SqlDouble GetSqlDouble(int i) {
  2020. ReadColumn(i);
  2021. return _data[i].SqlDouble;
  2022. }
  2023. virtual public SqlInt16 GetSqlInt16(int i) {
  2024. ReadColumn(i);
  2025. return _data[i].SqlInt16;
  2026. }
  2027. virtual public SqlInt32 GetSqlInt32(int i) {
  2028. ReadColumn(i);
  2029. return _data[i].SqlInt32;
  2030. }
  2031. virtual public SqlInt64 GetSqlInt64(int i) {
  2032. ReadColumn(i);
  2033. return _data[i].SqlInt64;
  2034. }
  2035. virtual public SqlMoney GetSqlMoney(int i) {
  2036. ReadColumn(i);
  2037. return _data[i].SqlMoney;
  2038. }
  2039. virtual public SqlSingle GetSqlSingle(int i) {
  2040. ReadColumn(i);
  2041. return _data[i].SqlSingle;
  2042. }
  2043. //
  2044. virtual public SqlString GetSqlString(int i) {
  2045. ReadColumn(i);
  2046. if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && _metaData[i].IsNewKatmaiDateTimeType) {
  2047. return _data[i].KatmaiDateTimeSqlString;
  2048. }
  2049. return _data[i].SqlString;
  2050. }
  2051. virtual public SqlXml GetSqlXml(int i){
  2052. ReadColumn(i);
  2053. SqlXml sx = null;
  2054. if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000) {
  2055. // TypeSystem.SQLServer2005
  2056. sx = _data[i].IsNull ? SqlXml.Null : _data[i].SqlCachedBuffer.ToSqlXml();
  2057. }
  2058. else {
  2059. // TypeSystem.SQLServer2000
  2060. // First, attempt to obtain SqlXml value. If not SqlXml, we will throw the appropriate
  2061. // cast exception.
  2062. sx = _data[i].IsNull ? SqlXml.Null : _data[i].SqlCachedBuffer.ToSqlXml();
  2063. // If the above succeeds, then we received a valid SqlXml instance, now we need to force
  2064. // an InvalidCastException since SqlXml is not exposed with the version knob in this setting.
  2065. // To do so, we simply force the exception by casting the string representation of the value
  2066. // To SqlXml.
  2067. object temp = (object) _data[i].String;
  2068. sx = (SqlXml) temp;
  2069. }
  2070. return sx;
  2071. }
  2072. virtual public object GetSqlValue(int i) {
  2073. SqlStatistics statistics = null;
  2074. try {
  2075. statistics = SqlStatistics.StartTimer(Statistics);
  2076. SetTimeout(_defaultTimeoutMilliseconds);
  2077. return GetSqlValueInternal(i);
  2078. }
  2079. finally {
  2080. SqlStatistics.StopTimer(statistics);
  2081. }
  2082. }
  2083. private object GetSqlValueInternal(int i) {
  2084. if (_currentTask != null) {
  2085. throw ADP.AsyncOperationPending();
  2086. }
  2087. Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  2088. bool result = TryReadColumn(i, setTimeout: false);
  2089. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  2090. return GetSqlValueFromSqlBufferInternal(_data[i], _metaData[i]);
  2091. }
  2092. // NOTE: This method is called by the fast-paths in Async methods and, therefore, should be resilient to the DataReader being closed
  2093. // Always make sure to take reference copies of anything set to null in TryCloseInternal()
  2094. private object GetSqlValueFromSqlBufferInternal(SqlBuffer data, _SqlMetaData metaData) {
  2095. // Dev11 Bug #336820, Dev10 Bug #479607 (SqlClient: IsDBNull always returns false for timestamp datatype)
  2096. // Due to a bug in TdsParser.GetNullSqlValue, Timestamps' IsNull is not correctly set - so we need to bypass the following check
  2097. Debug.Assert(!data.IsEmpty || data.IsNull || metaData.type == SqlDbType.Timestamp, "Data has been read, but the buffer is empty");
  2098. // Convert Katmai types to string
  2099. if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType) {
  2100. return data.KatmaiDateTimeSqlString;
  2101. }
  2102. else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsLargeUdt) {
  2103. return data.SqlValue;
  2104. }
  2105. else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000) {
  2106. // TypeSystem.SQLServer2005
  2107. if (metaData.type == SqlDbType.Udt) {
  2108. var connection = _connection;
  2109. if (connection != null) {
  2110. connection.CheckGetExtendedUDTInfo(metaData, true);
  2111. return connection.GetUdtValue(data.Value, metaData, false);
  2112. }
  2113. else {
  2114. throw ADP.DataReaderClosed("GetSqlValueFromSqlBufferInternal");
  2115. }
  2116. }
  2117. else {
  2118. return data.SqlValue;
  2119. }
  2120. }
  2121. else {
  2122. // TypeSystem.SQLServer2000
  2123. if (metaData.type == SqlDbType.Xml) {
  2124. return data.SqlString;
  2125. }
  2126. else {
  2127. return data.SqlValue;
  2128. }
  2129. }
  2130. }
  2131. virtual public int GetSqlValues(object[] values){
  2132. SqlStatistics statistics = null;
  2133. try {
  2134. statistics = SqlStatistics.StartTimer(Statistics);
  2135. CheckDataIsReady();
  2136. if (null == values) {
  2137. throw ADP.ArgumentNull("values");
  2138. }
  2139. SetTimeout(_defaultTimeoutMilliseconds);
  2140. int copyLen = (values.Length < _metaData.visibleColumns) ? values.Length : _metaData.visibleColumns;
  2141. for (int i = 0; i < copyLen; i++) {
  2142. values[_metaData.indexMap[i]] = GetSqlValueInternal(i);
  2143. }
  2144. return copyLen;
  2145. }
  2146. finally {
  2147. SqlStatistics.StopTimer(statistics);
  2148. }
  2149. }
  2150. override public string GetString(int i) {
  2151. ReadColumn(i);
  2152. // Convert katmai value to string if type system knob is 2005 or earlier
  2153. if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && _metaData[i].IsNewKatmaiDateTimeType) {
  2154. return _data[i].KatmaiDateTimeString;
  2155. }
  2156. return _data[i].String;
  2157. }
  2158. override public T GetFieldValue<T>(int i) {
  2159. SqlStatistics statistics = null;
  2160. try {
  2161. statistics = SqlStatistics.StartTimer(Statistics);
  2162. SetTimeout(_defaultTimeoutMilliseconds);
  2163. return GetFieldValueInternal<T>(i);
  2164. }
  2165. finally {
  2166. SqlStatistics.StopTimer(statistics);
  2167. }
  2168. }
  2169. override public object GetValue(int i) {
  2170. SqlStatistics statistics = null;
  2171. try {
  2172. statistics = SqlStatistics.StartTimer(Statistics);
  2173. SetTimeout(_defaultTimeoutMilliseconds);
  2174. return GetValueInternal(i);
  2175. }
  2176. finally {
  2177. SqlStatistics.StopTimer(statistics);
  2178. }
  2179. }
  2180. virtual public TimeSpan GetTimeSpan(int i) {
  2181. ReadColumn(i);
  2182. TimeSpan t = _data[i].Time;
  2183. if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005) {
  2184. // TypeSystem.SQLServer2005 or less
  2185. // If the above succeeds, then we received a valid TimeSpan instance, now we need to force
  2186. // an InvalidCastException since TimeSpan is not exposed with the version knob in this setting.
  2187. // To do so, we simply force the exception by casting the string representation of the value
  2188. // To TimeSpan.
  2189. object temp = (object) _data[i].String;
  2190. t = (TimeSpan) temp;
  2191. }
  2192. return t;
  2193. }
  2194. virtual public DateTimeOffset GetDateTimeOffset(int i) {
  2195. ReadColumn(i);
  2196. DateTimeOffset dto = _data[i].DateTimeOffset;
  2197. if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005) {
  2198. // TypeSystem.SQLServer2005 or less
  2199. // If the above succeeds, then we received a valid DateTimeOffset instance, now we need to force
  2200. // an InvalidCastException since DateTime is not exposed with the version knob in this setting.
  2201. // To do so, we simply force the exception by casting the string representation of the value
  2202. // To DateTimeOffset.
  2203. object temp = (object) _data[i].String;
  2204. dto = (DateTimeOffset) temp;
  2205. }
  2206. return dto;
  2207. }
  2208. private object GetValueInternal(int i) {
  2209. if (_currentTask != null) {
  2210. throw ADP.AsyncOperationPending();
  2211. }
  2212. Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  2213. bool result = TryReadColumn(i, setTimeout: false);
  2214. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  2215. return GetValueFromSqlBufferInternal(_data[i], _metaData[i]);
  2216. }
  2217. // NOTE: This method is called by the fast-paths in Async methods and, therefore, should be resilient to the DataReader being closed
  2218. // Always make sure to take reference copies of anything set to null in TryCloseInternal()
  2219. private object GetValueFromSqlBufferInternal(SqlBuffer data, _SqlMetaData metaData) {
  2220. // Dev11 Bug #336820, Dev10 Bug #479607 (SqlClient: IsDBNull always returns false for timestamp datatype)
  2221. // Due to a bug in TdsParser.GetNullSqlValue, Timestamps' IsNull is not correctly set - so we need to bypass the following check
  2222. Debug.Assert(!data.IsEmpty || data.IsNull || metaData.type == SqlDbType.Timestamp, "Data has been read, but the buffer is empty");
  2223. if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType) {
  2224. if (data.IsNull) {
  2225. return DBNull.Value;
  2226. }
  2227. else {
  2228. return data.KatmaiDateTimeString;
  2229. }
  2230. }
  2231. else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsLargeUdt) {
  2232. return data.Value;
  2233. }
  2234. else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000) {
  2235. // TypeSystem.SQLServer2005
  2236. if (metaData.type != SqlDbType.Udt) {
  2237. return data.Value;
  2238. }
  2239. else {
  2240. var connection = _connection;
  2241. if (connection != null) {
  2242. connection.CheckGetExtendedUDTInfo(metaData, true);
  2243. return connection.GetUdtValue(data.Value, metaData, true);
  2244. }
  2245. else {
  2246. throw ADP.DataReaderClosed("GetValueFromSqlBufferInternal");
  2247. }
  2248. }
  2249. }
  2250. else {
  2251. // TypeSystem.SQLServer2000
  2252. return data.Value;
  2253. }
  2254. }
  2255. private T GetFieldValueInternal<T>(int i) {
  2256. if (_currentTask != null) {
  2257. throw ADP.AsyncOperationPending();
  2258. }
  2259. Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  2260. bool result = TryReadColumn(i, setTimeout: false);
  2261. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  2262. return GetFieldValueFromSqlBufferInternal<T>(_data[i], _metaData[i]);
  2263. }
  2264. private T GetFieldValueFromSqlBufferInternal<T>(SqlBuffer data, _SqlMetaData metaData) {
  2265. Type typeofT = typeof(T);
  2266. if (_typeofINullable.IsAssignableFrom(typeofT)) {
  2267. // If its a SQL Type or Nullable UDT
  2268. object rawValue = GetSqlValueFromSqlBufferInternal(data, metaData);
  2269. // Special case: User wants SqlString, but we have a SqlXml
  2270. // SqlXml can not be typecast into a SqlString, but we need to support SqlString on XML Types - so do a manual conversion
  2271. if (typeofT == _typeofSqlString) {
  2272. SqlXml xmlValue = rawValue as SqlXml;
  2273. if (xmlValue != null) {
  2274. if (xmlValue.IsNull) {
  2275. rawValue = SqlString.Null;
  2276. }
  2277. else {
  2278. rawValue = new SqlString(xmlValue.Value);
  2279. }
  2280. }
  2281. }
  2282. return (T)rawValue;
  2283. }
  2284. else {
  2285. // Otherwise Its a CLR or non-Nullable UDT
  2286. try {
  2287. return (T)GetValueFromSqlBufferInternal(data, metaData);
  2288. }
  2289. catch (InvalidCastException) {
  2290. if (data.IsNull) {
  2291. // If the value was actually null, then we should throw a SqlNullValue instead
  2292. throw SQL.SqlNullValue();
  2293. }
  2294. else {
  2295. // Legitmate InvalidCast, rethrow
  2296. throw;
  2297. }
  2298. }
  2299. }
  2300. }
  2301. override public int GetValues(object[] values) {
  2302. SqlStatistics statistics = null;
  2303. bool sequentialAccess = IsCommandBehavior(CommandBehavior.SequentialAccess);
  2304. try {
  2305. statistics = SqlStatistics.StartTimer(Statistics);
  2306. if (null == values) {
  2307. throw ADP.ArgumentNull("values");
  2308. }
  2309. CheckMetaDataIsReady();
  2310. int copyLen = (values.Length < _metaData.visibleColumns) ? values.Length : _metaData.visibleColumns;
  2311. int maximumColumn = copyLen - 1;
  2312. SetTimeout(_defaultTimeoutMilliseconds);
  2313. // Temporarily disable sequential access
  2314. _commandBehavior &= ~CommandBehavior.SequentialAccess;
  2315. // Read in all of the columns in one TryReadColumn call
  2316. bool result = TryReadColumn(maximumColumn, setTimeout: false);
  2317. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  2318. for (int i = 0; i < copyLen; i++) {
  2319. // Get the usable, TypeSystem-compatible value from the iternal buffer
  2320. values[_metaData.indexMap[i]] = GetValueFromSqlBufferInternal(_data[i], _metaData[i]);
  2321. // If this is sequential access, then we need to wipe the internal buffer
  2322. if ((sequentialAccess) && (i < maximumColumn)) {
  2323. _data[i].Clear();
  2324. }
  2325. }
  2326. return copyLen;
  2327. }
  2328. finally {
  2329. // Restore sequential access
  2330. if (sequentialAccess) {
  2331. _commandBehavior |= CommandBehavior.SequentialAccess;
  2332. }
  2333. SqlStatistics.StopTimer(statistics);
  2334. }
  2335. }
  2336. private MetaType GetVersionedMetaType(MetaType actualMetaType) {
  2337. Debug.Assert(_typeSystem == SqlConnectionString.TypeSystem.SQLServer2000, "Should not be in this function under anything else but SQLServer2000");
  2338. MetaType metaType = null;
  2339. if (actualMetaType == MetaType.MetaUdt) {
  2340. metaType = MetaType.MetaVarBinary;
  2341. }
  2342. else if (actualMetaType == MetaType.MetaXml) {
  2343. metaType = MetaType.MetaNText;
  2344. }
  2345. else if (actualMetaType == MetaType.MetaMaxVarBinary) {
  2346. metaType = MetaType.MetaImage;
  2347. }
  2348. else if (actualMetaType == MetaType.MetaMaxVarChar) {
  2349. metaType = MetaType.MetaText;
  2350. }
  2351. else if (actualMetaType == MetaType.MetaMaxNVarChar) {
  2352. metaType = MetaType.MetaNText;
  2353. }
  2354. else {
  2355. metaType = actualMetaType;
  2356. }
  2357. return metaType;
  2358. }
  2359. private bool TryHasMoreResults(out bool moreResults) {
  2360. if(null != _parser) {
  2361. bool moreRows;
  2362. if (!TryHasMoreRows(out moreRows)) {
  2363. moreResults = false;
  2364. return false;
  2365. }
  2366. if(moreRows) {
  2367. // When does this happen? This is only called from NextResult(), which loops until Read() false.
  2368. moreResults = false;
  2369. return true;
  2370. }
  2371. Debug.Assert(null != _command, "unexpected null command from the data reader!");
  2372. while(_stateObj._pendingData) {
  2373. byte token;
  2374. if (!_stateObj.TryPeekByte(out token)) {
  2375. moreResults = false;
  2376. return false;
  2377. }
  2378. switch(token) {
  2379. case TdsEnums.SQLALTROW:
  2380. if(_altRowStatus == ALTROWSTATUS.Null) {
  2381. // cache the regular metadata
  2382. _altMetaDataSetCollection.metaDataSet = _metaData;
  2383. _metaData = null;
  2384. }
  2385. else {
  2386. Debug.Assert(_altRowStatus == ALTROWSTATUS.Done, "invalid AltRowStatus");
  2387. }
  2388. _altRowStatus = ALTROWSTATUS.AltRow;
  2389. _hasRows = true;
  2390. moreResults = true;
  2391. return true;
  2392. case TdsEnums.SQLROW:
  2393. case TdsEnums.SQLNBCROW:
  2394. // always happens if there is a row following an altrow
  2395. moreResults = true;
  2396. return true;
  2397. // VSTFDEVDIV 926281: DONEINPROC case is missing here; we have decided to reject this bug as it would result in breaking change
  2398. // from Orcas RTM/SP1 and Dev10 RTM. See the bug for more details.
  2399. // case TdsEnums.DONEINPROC:
  2400. case TdsEnums.SQLDONE:
  2401. Debug.Assert(_altRowStatus == ALTROWSTATUS.Done || _altRowStatus == ALTROWSTATUS.Null, "invalid AltRowStatus");
  2402. _altRowStatus = ALTROWSTATUS.Null;
  2403. _metaData = null;
  2404. _altMetaDataSetCollection = null;
  2405. moreResults = true;
  2406. return true;
  2407. case TdsEnums.SQLCOLMETADATA:
  2408. moreResults = true;
  2409. return true;
  2410. }
  2411. // Dev11 Bug 316483:Hang on SqlDataReader::TryHasMoreResults using MARS
  2412. // http://vstfdevdiv:8080/web/wi.aspx?pcguid=22f9acc9-569a-41ff-b6ac-fac1b6370209&id=316483
  2413. // TryRun() will immediately return if the TdsParser is closed\broken, causing us to enter an infinite loop
  2414. // Instead, we will throw a closed connection exception
  2415. if (_parser.State == TdsParserState.Broken || _parser.State == TdsParserState.Closed) {
  2416. throw ADP.ClosedConnectionError();
  2417. }
  2418. bool ignored;
  2419. if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, this, null, _stateObj, out ignored)) {
  2420. moreResults = false;
  2421. return false;
  2422. }
  2423. }
  2424. }
  2425. moreResults = false;
  2426. return true;
  2427. }
  2428. private bool TryHasMoreRows(out bool moreRows) {
  2429. if (null != _parser) {
  2430. if (_sharedState._dataReady) {
  2431. moreRows = true;
  2432. return true;
  2433. }
  2434. // NextResult: previous call to NextResult started to process the altrowpackage, can't peek anymore
  2435. // Read: Read prepared for final processing of altrow package, No more Rows until NextResult ...
  2436. // Done: Done processing the altrow, no more rows until NextResult ...
  2437. switch (_altRowStatus) {
  2438. case ALTROWSTATUS.AltRow:
  2439. moreRows = true;
  2440. return true;
  2441. case ALTROWSTATUS.Done:
  2442. moreRows = false;
  2443. return true;
  2444. }
  2445. if (_stateObj._pendingData) {
  2446. // Consume error's, info's, done's on HasMoreRows, so user obtains error on Read.
  2447. // Previous bug where Read() would return false with error on the wire in the case
  2448. // of metadata and error immediately following. See MDAC 78285 and 75225.
  2449. //
  2450. // process any done, doneproc and doneinproc token streams and
  2451. // any order, error or info token preceeding the first done, doneproc or doneinproc token stream
  2452. byte b;
  2453. if (!_stateObj.TryPeekByte(out b)) {
  2454. moreRows = false;
  2455. return false;
  2456. }
  2457. bool ParsedDoneToken = false;
  2458. while ( b == TdsEnums.SQLDONE ||
  2459. b == TdsEnums.SQLDONEPROC ||
  2460. b == TdsEnums.SQLDONEINPROC ||
  2461. !ParsedDoneToken && (
  2462. b == TdsEnums.SQLSESSIONSTATE ||
  2463. b == TdsEnums.SQLENVCHANGE ||
  2464. b == TdsEnums.SQLORDER ||
  2465. b == TdsEnums.SQLERROR ||
  2466. b == TdsEnums.SQLINFO ) ) {
  2467. if (b == TdsEnums.SQLDONE ||
  2468. b == TdsEnums.SQLDONEPROC ||
  2469. b == TdsEnums.SQLDONEINPROC) {
  2470. ParsedDoneToken = true;
  2471. }
  2472. // Dev11 Bug 316483:Hang on SqlDataReader::TryHasMoreResults using MARS
  2473. // http://vstfdevdiv:8080/web/wi.aspx?pcguid=22f9acc9-569a-41ff-b6ac-fac1b6370209&id=316483
  2474. // TryRun() will immediately return if the TdsParser is closed\broken, causing us to enter an infinite loop
  2475. // Instead, we will throw a closed connection exception
  2476. if (_parser.State == TdsParserState.Broken || _parser.State == TdsParserState.Closed) {
  2477. throw ADP.ClosedConnectionError();
  2478. }
  2479. bool ignored;
  2480. if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, this, null, _stateObj, out ignored)) {
  2481. moreRows = false;
  2482. return false;
  2483. }
  2484. if ( _stateObj._pendingData) {
  2485. if (!_stateObj.TryPeekByte(out b)) {
  2486. moreRows = false;
  2487. return false;
  2488. }
  2489. }
  2490. else {
  2491. break;
  2492. }
  2493. }
  2494. // Only return true when we are positioned on a row token.
  2495. if (IsRowToken(b)) {
  2496. moreRows = true;
  2497. return true;
  2498. }
  2499. }
  2500. }
  2501. moreRows = false;
  2502. return true;
  2503. }
  2504. private bool IsRowToken(byte token) {
  2505. return TdsEnums.SQLROW == token || TdsEnums.SQLNBCROW == token;
  2506. }
  2507. override public bool IsDBNull(int i) {
  2508. if ((IsCommandBehavior(CommandBehavior.SequentialAccess)) && ((_sharedState._nextColumnHeaderToRead > i + 1) || (_lastColumnWithDataChunkRead > i))) {
  2509. // Bug 447026 : A breaking change in System.Data .NET 4.5 for calling IsDBNull on commands in SequentialAccess mode
  2510. // http://vstfdevdiv:8080/web/wi.aspx?pcguid=22f9acc9-569a-41ff-b6ac-fac1b6370209&id=447026
  2511. // In .Net 4.0 and previous, it was possible to read a previous column using IsDBNull when in sequential mode
  2512. // However, since it had already gone past the column, the current IsNull value is simply returned
  2513. // To replicate this behavior we will skip CheckHeaderIsReady\ReadColumnHeader and instead just check that the reader is ready and the column is valid
  2514. CheckMetaDataIsReady(columnIndex: i);
  2515. }
  2516. else {
  2517. CheckHeaderIsReady(columnIndex: i, methodName: "IsDBNull");
  2518. SetTimeout(_defaultTimeoutMilliseconds);
  2519. ReadColumnHeader(i); // header data only
  2520. }
  2521. return _data[i].IsNull;
  2522. }
  2523. protected internal bool IsCommandBehavior(CommandBehavior condition) {
  2524. return (condition == (condition & _commandBehavior));
  2525. }
  2526. override public bool NextResult() {
  2527. if (_currentTask != null) {
  2528. throw SQL.PendingBeginXXXExists();
  2529. }
  2530. bool more;
  2531. bool result;
  2532. Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  2533. result = TryNextResult(out more);
  2534. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  2535. return more;
  2536. }
  2537. // recordset is automatically positioned on the first result set
  2538. private bool TryNextResult(out bool more) {
  2539. SqlStatistics statistics = null;
  2540. IntPtr hscp;
  2541. Bid.ScopeEnter(out hscp, "<sc.SqlDataReader.NextResult|API> %d#", ObjectID);
  2542. RuntimeHelpers.PrepareConstrainedRegions();
  2543. try {
  2544. #if DEBUG
  2545. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  2546. RuntimeHelpers.PrepareConstrainedRegions();
  2547. try {
  2548. tdsReliabilitySection.Start();
  2549. #else
  2550. {
  2551. #endif //DEBUG
  2552. statistics = SqlStatistics.StartTimer(Statistics);
  2553. SetTimeout(_defaultTimeoutMilliseconds);
  2554. if (IsClosed) {
  2555. throw ADP.DataReaderClosed("NextResult");
  2556. }
  2557. _fieldNameLookup = null;
  2558. bool success = false; // WebData 100390
  2559. _hasRows = false; // reset HasRows
  2560. // if we are specifically only processing a single result, then read all the results off the wire and detach
  2561. if (IsCommandBehavior(CommandBehavior.SingleResult)) {
  2562. if (!TryCloseInternal(false /*closeReader*/)) {
  2563. more = false;
  2564. return false;
  2565. }
  2566. // In the case of not closing the reader, null out the metadata AFTER
  2567. // CloseInternal finishes - since CloseInternal may go to the wire
  2568. // and use the metadata.
  2569. ClearMetaData();
  2570. more = success;
  2571. return true;
  2572. }
  2573. if (null != _parser) {
  2574. // if there are more rows, then skip them, the user wants the next result
  2575. bool moreRows = true;
  2576. while (moreRows) {
  2577. if (!TryReadInternal(false, out moreRows)) { // don't reset set the timeout value
  2578. more = false;
  2579. return false;
  2580. }
  2581. }
  2582. }
  2583. // we may be done, so continue only if we have not detached ourselves from the parser
  2584. if (null != _parser) {
  2585. bool moreResults;
  2586. if (!TryHasMoreResults(out moreResults)) {
  2587. more = false;
  2588. return false;
  2589. }
  2590. if (moreResults) {
  2591. _metaDataConsumed = false;
  2592. _browseModeInfoConsumed = false;
  2593. switch (_altRowStatus) {
  2594. case ALTROWSTATUS.AltRow:
  2595. int altRowId;
  2596. if (!_parser.TryGetAltRowId(_stateObj, out altRowId)) {
  2597. more = false;
  2598. return false;
  2599. }
  2600. _SqlMetaDataSet altMetaDataSet = _altMetaDataSetCollection.GetAltMetaData(altRowId);
  2601. if (altMetaDataSet != null) {
  2602. _metaData = altMetaDataSet;
  2603. }
  2604. Debug.Assert ((_metaData != null), "Can't match up altrowmetadata");
  2605. break;
  2606. case ALTROWSTATUS.Done:
  2607. // restore the row-metaData
  2608. _metaData = _altMetaDataSetCollection.metaDataSet;
  2609. Debug.Assert (_altRowStatus == ALTROWSTATUS.Done, "invalid AltRowStatus");
  2610. _altRowStatus = ALTROWSTATUS.Null;
  2611. break;
  2612. default:
  2613. if (!TryConsumeMetaData()) {
  2614. more = false;
  2615. return false;
  2616. }
  2617. if (_metaData == null) {
  2618. more = false;
  2619. return true;
  2620. }
  2621. break;
  2622. }
  2623. success = true;
  2624. }
  2625. else {
  2626. // detach the parser from this reader now
  2627. if (!TryCloseInternal(false /*closeReader*/)) {
  2628. more = false;
  2629. return false;
  2630. }
  2631. // In the case of not closing the reader, null out the metadata AFTER
  2632. // CloseInternal finishes - since CloseInternal may go to the wire
  2633. // and use the metadata.
  2634. if (!TrySetMetaData(null, false)) {
  2635. more = false;
  2636. return false;
  2637. }
  2638. }
  2639. }
  2640. else {
  2641. // Clear state in case of Read calling CloseInternal() then user calls NextResult()
  2642. // MDAC 81986. Or, also the case where the Read() above will do essentially the same
  2643. // thing.
  2644. ClearMetaData();
  2645. }
  2646. more = success;
  2647. return true;
  2648. }
  2649. #if DEBUG
  2650. finally {
  2651. tdsReliabilitySection.Stop();
  2652. }
  2653. #endif //DEBUG
  2654. }
  2655. catch (System.OutOfMemoryException e) {
  2656. _isClosed = true;
  2657. if (null != _connection) {
  2658. _connection.Abort(e);
  2659. }
  2660. throw;
  2661. }
  2662. catch (System.StackOverflowException e) {
  2663. _isClosed = true;
  2664. if (null != _connection) {
  2665. _connection.Abort(e);
  2666. }
  2667. throw;
  2668. }
  2669. catch (System.Threading.ThreadAbortException e) {
  2670. _isClosed = true;
  2671. if (null != _connection) {
  2672. _connection.Abort(e);
  2673. }
  2674. throw;
  2675. }
  2676. finally {
  2677. SqlStatistics.StopTimer(statistics);
  2678. Bid.ScopeLeave(ref hscp);
  2679. }
  2680. }
  2681. // user must call Read() to position on the first row
  2682. override public bool Read() {
  2683. if (_currentTask != null) {
  2684. throw SQL.PendingBeginXXXExists();
  2685. }
  2686. bool more;
  2687. bool result;
  2688. Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  2689. result = TryReadInternal(true, out more);
  2690. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  2691. return more;
  2692. }
  2693. // user must call Read() to position on the first row
  2694. private bool TryReadInternal(bool setTimeout, out bool more) {
  2695. SqlStatistics statistics = null;
  2696. IntPtr hscp;
  2697. Bid.ScopeEnter(out hscp, "<sc.SqlDataReader.Read|API> %d#", ObjectID);
  2698. RuntimeHelpers.PrepareConstrainedRegions();
  2699. try {
  2700. #if DEBUG
  2701. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  2702. RuntimeHelpers.PrepareConstrainedRegions();
  2703. try {
  2704. tdsReliabilitySection.Start();
  2705. #else
  2706. {
  2707. #endif //DEBUG
  2708. statistics = SqlStatistics.StartTimer(Statistics);
  2709. if (null != _parser) {
  2710. if (setTimeout) {
  2711. SetTimeout(_defaultTimeoutMilliseconds);
  2712. }
  2713. if (_sharedState._dataReady) {
  2714. if (!TryCleanPartialRead()) {
  2715. more = false;
  2716. return false;
  2717. }
  2718. }
  2719. // clear out our buffers
  2720. SqlBuffer.Clear(_data);
  2721. _sharedState._nextColumnHeaderToRead = 0;
  2722. _sharedState._nextColumnDataToRead = 0;
  2723. _sharedState._columnDataBytesRemaining = -1; // unknown
  2724. _lastColumnWithDataChunkRead = -1;
  2725. if (!_haltRead) {
  2726. bool moreRows;
  2727. if (!TryHasMoreRows(out moreRows)) {
  2728. more = false;
  2729. return false;
  2730. }
  2731. if (moreRows) {
  2732. // read the row from the backend (unless it's an altrow were the marker is already inside the altrow ...)
  2733. while (_stateObj._pendingData) {
  2734. if (_altRowStatus != ALTROWSTATUS.AltRow) {
  2735. // if this is an ordinary row we let the run method consume the ROW token
  2736. if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, this, null, _stateObj, out _sharedState._dataReady)) {
  2737. more = false;
  2738. return false;
  2739. }
  2740. if (_sharedState._dataReady) {
  2741. break;
  2742. }
  2743. }
  2744. else {
  2745. // ALTROW token and AltrowId are already consumed ...
  2746. Debug.Assert (_altRowStatus == ALTROWSTATUS.AltRow, "invalid AltRowStatus");
  2747. _altRowStatus = ALTROWSTATUS.Done;
  2748. _sharedState._dataReady = true;
  2749. break;
  2750. }
  2751. }
  2752. if (_sharedState._dataReady) {
  2753. _haltRead = IsCommandBehavior(CommandBehavior.SingleRow);
  2754. more = true;
  2755. return true;
  2756. }
  2757. }
  2758. if (!_stateObj._pendingData) {
  2759. if (!TryCloseInternal(false /*closeReader*/)) {
  2760. more = false;
  2761. return false;
  2762. }
  2763. }
  2764. }
  2765. else {
  2766. // if we did not get a row and halt is true, clean off rows of result
  2767. // success must be false - or else we could have just read off row and set
  2768. // halt to true
  2769. bool moreRows;
  2770. if (!TryHasMoreRows(out moreRows)) {
  2771. more = false;
  2772. return false;
  2773. }
  2774. while (moreRows) {
  2775. // if we are in SingleRow mode, and we've read the first row,
  2776. // read the rest of the rows, if any
  2777. while (_stateObj._pendingData && !_sharedState._dataReady) {
  2778. if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, this, null, _stateObj, out _sharedState._dataReady)) {
  2779. more = false;
  2780. return false;
  2781. }
  2782. }
  2783. if (_sharedState._dataReady) {
  2784. if (!TryCleanPartialRead()) {
  2785. more = false;
  2786. return false;
  2787. }
  2788. }
  2789. // clear out our buffers
  2790. SqlBuffer.Clear(_data);
  2791. _sharedState._nextColumnHeaderToRead = 0;
  2792. if (!TryHasMoreRows(out moreRows)) {
  2793. more = false;
  2794. return false;
  2795. }
  2796. }
  2797. // reset haltRead
  2798. _haltRead = false;
  2799. }
  2800. }
  2801. else if (IsClosed) {
  2802. throw ADP.DataReaderClosed("Read");
  2803. }
  2804. more = false;
  2805. #if DEBUG
  2806. if ((!_sharedState._dataReady) && (_stateObj._pendingData)) {
  2807. byte token;
  2808. if (!_stateObj.TryPeekByte(out token)) {
  2809. return false;
  2810. }
  2811. Debug.Assert(TdsParser.IsValidTdsToken(token), string.Format("DataReady is false, but next token is invalid: {0,-2:X2}", token));
  2812. }
  2813. #endif
  2814. return true;
  2815. }
  2816. #if DEBUG
  2817. finally {
  2818. tdsReliabilitySection.Stop();
  2819. }
  2820. #endif //DEBUG
  2821. }
  2822. catch (System.OutOfMemoryException e) {
  2823. _isClosed = true;
  2824. SqlConnection con = _connection;
  2825. if (con != null) {
  2826. con.Abort(e);
  2827. }
  2828. throw;
  2829. }
  2830. catch (System.StackOverflowException e) {
  2831. _isClosed = true;
  2832. SqlConnection con = _connection;
  2833. if (con != null) {
  2834. con.Abort(e);
  2835. }
  2836. throw;
  2837. }
  2838. catch (System.Threading.ThreadAbortException e) {
  2839. _isClosed = true;
  2840. SqlConnection con = _connection;
  2841. if (con != null) {
  2842. con.Abort(e);
  2843. }
  2844. throw;
  2845. }
  2846. finally {
  2847. SqlStatistics.StopTimer(statistics);
  2848. Bid.ScopeLeave(ref hscp);
  2849. }
  2850. }
  2851. private void ReadColumn(int i, bool setTimeout = true, bool allowPartiallyReadColumn = false) {
  2852. if (_currentTask != null) {
  2853. throw ADP.AsyncOperationPending();
  2854. }
  2855. Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  2856. bool result = TryReadColumn(i, setTimeout, allowPartiallyReadColumn);
  2857. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  2858. }
  2859. private bool TryReadColumn(int i, bool setTimeout, bool allowPartiallyReadColumn = false) {
  2860. CheckDataIsReady(columnIndex: i, permitAsync: true, allowPartiallyReadColumn: allowPartiallyReadColumn);
  2861. RuntimeHelpers.PrepareConstrainedRegions();
  2862. try {
  2863. #if DEBUG
  2864. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  2865. RuntimeHelpers.PrepareConstrainedRegions();
  2866. try {
  2867. tdsReliabilitySection.Start();
  2868. #else
  2869. {
  2870. #endif //DEBUG
  2871. Debug.Assert(_sharedState._nextColumnHeaderToRead <= _metaData.Length, "_sharedState._nextColumnHeaderToRead too large");
  2872. Debug.Assert(_sharedState._nextColumnDataToRead <= _metaData.Length, "_sharedState._nextColumnDataToRead too large");
  2873. if (setTimeout) {
  2874. SetTimeout(_defaultTimeoutMilliseconds);
  2875. }
  2876. if (!TryReadColumnInternal(i, readHeaderOnly: false)) {
  2877. return false;
  2878. }
  2879. Debug.Assert(null != _data[i], " data buffer is null?");
  2880. }
  2881. #if DEBUG
  2882. finally {
  2883. tdsReliabilitySection.Stop();
  2884. }
  2885. #endif //DEBUG
  2886. }
  2887. catch (System.OutOfMemoryException e) {
  2888. _isClosed = true;
  2889. if (null != _connection) {
  2890. _connection.Abort(e);
  2891. }
  2892. throw;
  2893. }
  2894. catch (System.StackOverflowException e) {
  2895. _isClosed = true;
  2896. if (null != _connection) {
  2897. _connection.Abort(e);
  2898. }
  2899. throw;
  2900. }
  2901. catch (System.Threading.ThreadAbortException e) {
  2902. _isClosed = true;
  2903. if (null != _connection) {
  2904. _connection.Abort(e);
  2905. }
  2906. throw;
  2907. }
  2908. return true;
  2909. }
  2910. private bool TryReadColumnData() {
  2911. // If we've already read the value (because it was NULL) we don't
  2912. // bother to read here.
  2913. if (!_data[_sharedState._nextColumnDataToRead].IsNull) {
  2914. _SqlMetaData columnMetaData = _metaData[_sharedState._nextColumnDataToRead];
  2915. if (!_parser.TryReadSqlValue(_data[_sharedState._nextColumnDataToRead], columnMetaData, (int)_sharedState._columnDataBytesRemaining, _stateObj,
  2916. _command != null ? _command.ColumnEncryptionSetting : SqlCommandColumnEncryptionSetting.UseConnectionSetting,
  2917. columnMetaData.column)) { // will read UDTs as VARBINARY.
  2918. return false;
  2919. }
  2920. _sharedState._columnDataBytesRemaining = 0;
  2921. }
  2922. _sharedState._nextColumnDataToRead++;
  2923. return true;
  2924. }
  2925. private void ReadColumnHeader(int i) {
  2926. Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
  2927. bool result = TryReadColumnHeader(i);
  2928. if (!result) { throw SQL.SynchronousCallMayNotPend(); }
  2929. }
  2930. private bool TryReadColumnHeader(int i) {
  2931. if (!_sharedState._dataReady) {
  2932. throw SQL.InvalidRead();
  2933. }
  2934. RuntimeHelpers.PrepareConstrainedRegions();
  2935. try {
  2936. #if DEBUG
  2937. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  2938. RuntimeHelpers.PrepareConstrainedRegions();
  2939. try {
  2940. tdsReliabilitySection.Start();
  2941. #endif //DEBUG
  2942. return TryReadColumnInternal(i, readHeaderOnly: true);
  2943. #if DEBUG
  2944. }
  2945. finally {
  2946. tdsReliabilitySection.Stop();
  2947. }
  2948. #endif //DEBUG
  2949. }
  2950. catch (System.OutOfMemoryException e) {
  2951. _isClosed = true;
  2952. if (null != _connection) {
  2953. _connection.Abort(e);
  2954. }
  2955. throw;
  2956. }
  2957. catch (System.StackOverflowException e) {
  2958. _isClosed = true;
  2959. if (null != _connection) {
  2960. _connection.Abort(e);
  2961. }
  2962. throw;
  2963. }
  2964. catch (System.Threading.ThreadAbortException e) {
  2965. _isClosed = true;
  2966. if (null != _connection) {
  2967. _connection.Abort(e);
  2968. }
  2969. throw;
  2970. }
  2971. }
  2972. private bool TryReadColumnInternal(int i, bool readHeaderOnly = false) {
  2973. AssertReaderState(requireData: true, permitAsync: true, columnIndex: i);
  2974. // Check if we've already read the header already
  2975. if (i < _sharedState._nextColumnHeaderToRead) {
  2976. // Read the header, but we need to read the data
  2977. if ((i == _sharedState._nextColumnDataToRead) && (!readHeaderOnly)) {
  2978. return TryReadColumnData();
  2979. }
  2980. // Else we've already read the data, or we're reading the header only
  2981. else {
  2982. // Ensure that, if we've read past the column, then we did store its data
  2983. Debug.Assert(i == _sharedState._nextColumnDataToRead || // Either we haven't read the column yet
  2984. ((i + 1 < _sharedState._nextColumnDataToRead) && (IsCommandBehavior(CommandBehavior.SequentialAccess))) || // Or we're in sequential mode and we've read way past the column (i.e. it was not the last column we read)
  2985. (!_data[i].IsEmpty || _data[i].IsNull) || // Or we should have data stored for the column (unless the column was null)
  2986. (_metaData[i].type == SqlDbType.Timestamp), // Or Dev11 Bug #336820, Dev10 Bug #479607 (SqlClient: IsDBNull always returns false for timestamp datatype)
  2987. // Due to a bug in TdsParser.GetNullSqlValue, Timestamps' IsNull is not correctly set - so we need to bypass the check
  2988. "Gone past column, be we have no data stored for it");
  2989. return true;
  2990. }
  2991. }
  2992. Debug.Assert(_data[i].IsEmpty || _data[i].IsNull, "re-reading column value?");
  2993. // If we're in sequential access mode, we can safely clear out any
  2994. // data from the previous column.
  2995. bool isSequentialAccess = IsCommandBehavior(CommandBehavior.SequentialAccess);
  2996. if (isSequentialAccess) {
  2997. if (0 < _sharedState._nextColumnDataToRead) {
  2998. _data[_sharedState._nextColumnDataToRead - 1].Clear();
  2999. }
  3000. // Only wipe out the blob objects if they aren't for a 'future' column (i.e. we haven't read up to them yet)
  3001. if ((_lastColumnWithDataChunkRead > -1) && (i > _lastColumnWithDataChunkRead)) {
  3002. CloseActiveSequentialStreamAndTextReader();
  3003. }
  3004. }
  3005. else if (_sharedState._nextColumnDataToRead < _sharedState._nextColumnHeaderToRead) {
  3006. // We read the header but not the column for the previous column
  3007. if (!TryReadColumnData()) {
  3008. return false;
  3009. }
  3010. Debug.Assert(_sharedState._nextColumnDataToRead == _sharedState._nextColumnHeaderToRead);
  3011. }
  3012. // if we still have bytes left from the previous blob read, clear the wire and reset
  3013. if (!TryResetBlobState()) {
  3014. return false;
  3015. }
  3016. do {
  3017. _SqlMetaData columnMetaData = _metaData[_sharedState._nextColumnHeaderToRead];
  3018. if ((isSequentialAccess) && (_sharedState._nextColumnHeaderToRead < i)) {
  3019. // SkipValue is no-op if the column appears in NBC bitmask
  3020. // if not, it skips regular and PLP types
  3021. if (!_parser.TrySkipValue(columnMetaData, _sharedState._nextColumnHeaderToRead, _stateObj)) {
  3022. return false;
  3023. }
  3024. _sharedState._nextColumnDataToRead = _sharedState._nextColumnHeaderToRead;
  3025. _sharedState._nextColumnHeaderToRead++;
  3026. }
  3027. else {
  3028. bool isNull;
  3029. ulong dataLength;
  3030. if (!_parser.TryProcessColumnHeader(columnMetaData, _stateObj, _sharedState._nextColumnHeaderToRead, out isNull, out dataLength)) {
  3031. return false;
  3032. }
  3033. _sharedState._nextColumnDataToRead = _sharedState._nextColumnHeaderToRead;
  3034. _sharedState._nextColumnHeaderToRead++; // We read this one
  3035. if (isNull && columnMetaData.type != SqlDbType.Timestamp /* Maintain behavior for known bug (Dev10 479607) rejected as breaking change - See comments in GetNullSqlValue for timestamp */)
  3036. {
  3037. TdsParser.GetNullSqlValue(_data[_sharedState._nextColumnDataToRead],
  3038. columnMetaData,
  3039. _command != null ? _command.ColumnEncryptionSetting : SqlCommandColumnEncryptionSetting.UseConnectionSetting,
  3040. _parser.Connection);
  3041. if (!readHeaderOnly) {
  3042. _sharedState._nextColumnDataToRead++;
  3043. }
  3044. }
  3045. else {
  3046. if ((i > _sharedState._nextColumnDataToRead) || (!readHeaderOnly)) {
  3047. // If we're not in sequential access mode, we have to
  3048. // save the data we skip over so that the consumer
  3049. // can read it out of order
  3050. if (!_parser.TryReadSqlValue(_data[_sharedState._nextColumnDataToRead], columnMetaData, (int)dataLength, _stateObj,
  3051. _command != null ? _command.ColumnEncryptionSetting : SqlCommandColumnEncryptionSetting.UseConnectionSetting,
  3052. columnMetaData.column)) { // will read UDTs as VARBINARY.
  3053. return false;
  3054. }
  3055. _sharedState._nextColumnDataToRead++;
  3056. }
  3057. else {
  3058. _sharedState._columnDataBytesRemaining = (long)dataLength;
  3059. }
  3060. }
  3061. }
  3062. if (_snapshot != null) {
  3063. // reset snapshot to save memory use. We can safely do that here because all SqlDataReader values are stable.
  3064. // The retry logic can use the current values to get back to the right state.
  3065. _snapshot = null;
  3066. PrepareAsyncInvocation(useSnapshot: true);
  3067. }
  3068. } while (_sharedState._nextColumnHeaderToRead <= i);
  3069. return true;
  3070. }
  3071. // Estimates if there is enough data available to read the number of columns requested
  3072. private bool WillHaveEnoughData(int targetColumn, bool headerOnly = false) {
  3073. AssertReaderState(requireData: true, permitAsync: true, columnIndex: targetColumn);
  3074. if ((_lastColumnWithDataChunkRead == _sharedState._nextColumnDataToRead) && (_metaData[_lastColumnWithDataChunkRead].metaType.IsPlp)) {
  3075. // In the middle of reading a Plp - no idea how much is left
  3076. return false;
  3077. }
  3078. int bytesRemaining = Math.Min(checked(_stateObj._inBytesRead - _stateObj._inBytesUsed), _stateObj._inBytesPacket);
  3079. // There are some parts of our code that peeks at the next token after doing its read
  3080. // So we will make sure that there is always a spare byte for it to look at
  3081. bytesRemaining--;
  3082. if ((targetColumn >= _sharedState._nextColumnDataToRead) && (_sharedState._nextColumnDataToRead < _sharedState._nextColumnHeaderToRead)) {
  3083. if (_sharedState._columnDataBytesRemaining > bytesRemaining) {
  3084. // The current column needs more data than we currently have
  3085. // NOTE: Since the Long data types (TEXT, IMAGE, NTEXT) can have a size of Int32.MaxValue we cannot simply subtract
  3086. // _columnDataBytesRemaining from bytesRemaining and then compare it to zero as this may lead to an overflow
  3087. return false;
  3088. }
  3089. else {
  3090. // Already read the header, so subtract actual data size
  3091. bytesRemaining = checked(bytesRemaining - (int)_sharedState._columnDataBytesRemaining);
  3092. }
  3093. }
  3094. // For each column that we need to read, subtract the size of its header and the size of its data
  3095. int currentColumn = _sharedState._nextColumnHeaderToRead;
  3096. while ((bytesRemaining >= 0) && (currentColumn <= targetColumn)) {
  3097. // Check NBC first
  3098. if (!_stateObj.IsNullCompressionBitSet(currentColumn)) {
  3099. // NOTE: This is mostly duplicated from TryProcessColumnHeaderNoNBC and TryGetTokenLength
  3100. var metaType = _metaData[currentColumn].metaType;
  3101. if ((metaType.IsLong) || (metaType.IsPlp) || (metaType.SqlDbType == SqlDbType.Udt) || (metaType.SqlDbType == SqlDbType.Structured)) {
  3102. // Plp, Udt and TVP types have an unknownable size - so return that the estimate failed
  3103. return false;
  3104. }
  3105. int maxHeaderSize;
  3106. byte typeAndMask = (byte)(_metaData[currentColumn].tdsType & TdsEnums.SQLLenMask);
  3107. if ((typeAndMask == TdsEnums.SQLVarLen) || (typeAndMask == TdsEnums.SQLVarCnt)) {
  3108. if (0 != (_metaData[currentColumn].tdsType & 0x80)) {
  3109. // UInt16 represents size
  3110. maxHeaderSize = 2;
  3111. }
  3112. else if (0 == (_metaData[currentColumn].tdsType & 0x0c)) {
  3113. // UInt32 represents size
  3114. maxHeaderSize = 4;
  3115. }
  3116. else {
  3117. // Byte represents size
  3118. maxHeaderSize = 1;
  3119. }
  3120. }
  3121. else
  3122. {
  3123. maxHeaderSize = 0;
  3124. }
  3125. bytesRemaining = checked(bytesRemaining - maxHeaderSize);
  3126. if ((currentColumn < targetColumn) || (!headerOnly)) {
  3127. bytesRemaining = checked(bytesRemaining - _metaData[currentColumn].length);
  3128. }
  3129. }
  3130. currentColumn++;
  3131. }
  3132. return (bytesRemaining >= 0);
  3133. }
  3134. // clean remainder bytes for the column off the wire
  3135. private bool TryResetBlobState() {
  3136. Debug.Assert(null != _stateObj, "null state object"); // _parser may be null at this point
  3137. AssertReaderState(requireData: true, permitAsync: true);
  3138. Debug.Assert(_sharedState._nextColumnHeaderToRead <= _metaData.Length, "_sharedState._nextColumnHeaderToRead too large");
  3139. // If we haven't already entirely read the column
  3140. if (_sharedState._nextColumnDataToRead < _sharedState._nextColumnHeaderToRead) {
  3141. if ((_sharedState._nextColumnHeaderToRead > 0) && (_metaData[_sharedState._nextColumnHeaderToRead - 1].metaType.IsPlp)) {
  3142. if (_stateObj._longlen != 0) {
  3143. ulong ignored;
  3144. if (!_stateObj.Parser.TrySkipPlpValue(UInt64.MaxValue, _stateObj, out ignored)) {
  3145. return false;
  3146. }
  3147. }
  3148. if (_streamingXml != null) {
  3149. SqlStreamingXml localSXml = _streamingXml;
  3150. _streamingXml = null;
  3151. localSXml.Close();
  3152. }
  3153. }
  3154. else if (0 < _sharedState._columnDataBytesRemaining) {
  3155. if (!_stateObj.TrySkipLongBytes(_sharedState._columnDataBytesRemaining)) {
  3156. return false;
  3157. }
  3158. }
  3159. }
  3160. #if DEBUG
  3161. else {
  3162. Debug.Assert((_sharedState._columnDataBytesRemaining == 0 || _sharedState._columnDataBytesRemaining == -1) && _stateObj._longlen == 0, "Haven't read header yet, but column is partially read?");
  3163. }
  3164. #endif
  3165. _sharedState._columnDataBytesRemaining = 0;
  3166. _columnDataBytesRead = 0;
  3167. _columnDataCharsRead = 0;
  3168. _columnDataChars = null;
  3169. _columnDataCharsIndex = -1;
  3170. _stateObj._plpdecoder = null;
  3171. return true;
  3172. }
  3173. private void CloseActiveSequentialStreamAndTextReader() {
  3174. if (_currentStream != null) {
  3175. _currentStream.SetClosed();
  3176. _currentStream = null;
  3177. }
  3178. if (_currentTextReader != null) {
  3179. _currentTextReader.SetClosed();
  3180. _currentStream = null;
  3181. }
  3182. }
  3183. private void RestoreServerSettings(TdsParser parser, TdsParserStateObject stateObj) {
  3184. // turn off any set options
  3185. if (null != parser && null != _resetOptionsString) {
  3186. // It is possible for this to be called during connection close on a
  3187. // broken connection, so check state first.
  3188. if (parser.State == TdsParserState.OpenLoggedIn) {
  3189. Bid.CorrelationTrace("<sc.SqlDataReader.RestoreServerSettings|Info|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
  3190. Task executeTask = parser.TdsExecuteSQLBatch(_resetOptionsString, (_command != null) ? _command.CommandTimeout : 0, null, stateObj, sync: true);
  3191. Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes");
  3192. // must execute this one synchronously as we can't retry
  3193. parser.Run(RunBehavior.UntilDone, _command, this, null, stateObj);
  3194. }
  3195. _resetOptionsString = null;
  3196. }
  3197. }
  3198. internal bool TrySetAltMetaDataSet(_SqlMetaDataSet metaDataSet, bool metaDataConsumed) {
  3199. if (_altMetaDataSetCollection == null) {
  3200. _altMetaDataSetCollection = new _SqlMetaDataSetCollection();
  3201. }
  3202. else if (_snapshot != null && object.ReferenceEquals(_snapshot._altMetaDataSetCollection, _altMetaDataSetCollection)) {
  3203. _altMetaDataSetCollection = (_SqlMetaDataSetCollection)_altMetaDataSetCollection.Clone();
  3204. }
  3205. _altMetaDataSetCollection.SetAltMetaData(metaDataSet);
  3206. _metaDataConsumed = metaDataConsumed;
  3207. if (_metaDataConsumed && null != _parser) {
  3208. byte b;
  3209. if (!_stateObj.TryPeekByte(out b)) {
  3210. return false;
  3211. }
  3212. if (TdsEnums.SQLORDER == b) {
  3213. bool ignored;
  3214. if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, this, null, _stateObj, out ignored)) {
  3215. return false;
  3216. }
  3217. if (!_stateObj.TryPeekByte(out b)) {
  3218. return false;
  3219. }
  3220. }
  3221. if (b == TdsEnums.SQLINFO) {
  3222. try {
  3223. _stateObj._accumulateInfoEvents = true;
  3224. bool ignored;
  3225. if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, null, null, _stateObj, out ignored)) {
  3226. return false;
  3227. }
  3228. }
  3229. finally {
  3230. _stateObj._accumulateInfoEvents = false;
  3231. }
  3232. if (!_stateObj.TryPeekByte(out b)) {
  3233. return false;
  3234. }
  3235. }
  3236. _hasRows = IsRowToken(b);
  3237. }
  3238. if (metaDataSet != null) {
  3239. if (_data == null || _data.Length<metaDataSet.Length) {
  3240. _data = SqlBuffer.CreateBufferArray(metaDataSet.Length);
  3241. }
  3242. }
  3243. return true;
  3244. }
  3245. private void ClearMetaData() {
  3246. _metaData = null;
  3247. _tableNames = null;
  3248. _fieldNameLookup = null;
  3249. _metaDataConsumed = false;
  3250. _browseModeInfoConsumed = false;
  3251. }
  3252. internal bool TrySetMetaData(_SqlMetaDataSet metaData, bool moreInfo) {
  3253. _metaData = metaData;
  3254. // get rid of cached metadata info as well
  3255. _tableNames = null;
  3256. if (_metaData != null) {
  3257. _metaData.schemaTable = null;
  3258. _data = SqlBuffer.CreateBufferArray(metaData.Length);
  3259. }
  3260. _fieldNameLookup = null;
  3261. if (null != metaData) {
  3262. // we are done consuming metadata only if there is no moreInfo
  3263. if (!moreInfo) {
  3264. _metaDataConsumed = true;
  3265. if (_parser != null) { // There is a valid case where parser is null
  3266. // Peek, and if row token present, set _hasRows true since there is a
  3267. // row in the result
  3268. byte b;
  3269. if (!_stateObj.TryPeekByte(out b)) {
  3270. return false;
  3271. }
  3272. //
  3273. // simply rip the order token off the wire
  3274. if (b == TdsEnums.SQLORDER) { // same logic as SetAltMetaDataSet
  3275. // Devnote: That's not the right place to process TDS
  3276. // Can this result in Reentrance to Run?
  3277. //
  3278. bool ignored;
  3279. if (!_parser.TryRun(RunBehavior.ReturnImmediately, null, null, null, _stateObj, out ignored)) {
  3280. return false;
  3281. }
  3282. if (!_stateObj.TryPeekByte(out b)) {
  3283. return false;
  3284. }
  3285. }
  3286. if (b == TdsEnums.SQLINFO)
  3287. {
  3288. // VSTFDEVDIV713926
  3289. // We are accumulating informational events and fire them at next
  3290. // TdsParser.Run purely to avoid breaking change
  3291. try {
  3292. _stateObj._accumulateInfoEvents = true;
  3293. bool ignored;
  3294. if (!_parser.TryRun(RunBehavior.ReturnImmediately, null, null, null, _stateObj, out ignored)) {
  3295. return false;
  3296. }
  3297. }
  3298. finally {
  3299. _stateObj._accumulateInfoEvents = false;
  3300. }
  3301. if (!_stateObj.TryPeekByte(out b)) {
  3302. return false;
  3303. }
  3304. }
  3305. _hasRows = IsRowToken(b);
  3306. if (TdsEnums.SQLALTMETADATA == b)
  3307. {
  3308. _metaDataConsumed = false;
  3309. }
  3310. }
  3311. }
  3312. }
  3313. else {
  3314. _metaDataConsumed = false;
  3315. }
  3316. _browseModeInfoConsumed = false;
  3317. return true;
  3318. }
  3319. private void SetTimeout(long timeoutMilliseconds) {
  3320. // WebData 111653,112003 -- we now set timeouts per operation, not
  3321. // per command (it's not supposed to be a cumulative per command).
  3322. TdsParserStateObject stateObj = _stateObj;
  3323. if (null != stateObj) {
  3324. stateObj.SetTimeoutMilliseconds(timeoutMilliseconds);
  3325. }
  3326. }
  3327. private bool HasActiveStreamOrTextReaderOnColumn(int columnIndex) {
  3328. bool active = false;
  3329. active |= ((_currentStream != null) && (_currentStream.ColumnIndex == columnIndex));
  3330. active |= ((_currentTextReader != null) && (_currentTextReader.ColumnIndex == columnIndex));
  3331. return active;
  3332. }
  3333. private void CheckMetaDataIsReady() {
  3334. if (_currentTask != null) {
  3335. throw ADP.AsyncOperationPending();
  3336. }
  3337. if (MetaData == null) {
  3338. throw SQL.InvalidRead();
  3339. }
  3340. }
  3341. private void CheckMetaDataIsReady(int columnIndex, bool permitAsync = false) {
  3342. if ((!permitAsync) && (_currentTask != null)) {
  3343. throw ADP.AsyncOperationPending();
  3344. }
  3345. if (MetaData == null) {
  3346. throw SQL.InvalidRead();
  3347. }
  3348. if ((columnIndex < 0) || (columnIndex >= _metaData.Length)) {
  3349. throw ADP.IndexOutOfRange();
  3350. }
  3351. }
  3352. private void CheckDataIsReady() {
  3353. if (_currentTask != null) {
  3354. throw ADP.AsyncOperationPending();
  3355. }
  3356. Debug.Assert(!_sharedState._dataReady || _metaData != null, "Data is ready, but there is no metadata?");
  3357. if ((!_sharedState._dataReady) || (_metaData == null)) {
  3358. throw SQL.InvalidRead();
  3359. }
  3360. }
  3361. private void CheckHeaderIsReady(int columnIndex, bool permitAsync = false, string methodName = null) {
  3362. if (_isClosed) {
  3363. throw ADP.DataReaderClosed(methodName ?? "CheckHeaderIsReady");
  3364. }
  3365. if ((!permitAsync) && (_currentTask != null)) {
  3366. throw ADP.AsyncOperationPending();
  3367. }
  3368. Debug.Assert(!_sharedState._dataReady || _metaData != null, "Data is ready, but there is no metadata?");
  3369. if ((!_sharedState._dataReady) || (_metaData == null)) {
  3370. throw SQL.InvalidRead();
  3371. }
  3372. if ((columnIndex < 0) || (columnIndex >= _metaData.Length)) {
  3373. throw ADP.IndexOutOfRange();
  3374. }
  3375. if ((IsCommandBehavior(CommandBehavior.SequentialAccess)) && // Only for sequential access
  3376. ((_sharedState._nextColumnHeaderToRead > columnIndex + 1) || (_lastColumnWithDataChunkRead > columnIndex))) { // Read past column
  3377. throw ADP.NonSequentialColumnAccess(columnIndex, Math.Max(_sharedState._nextColumnHeaderToRead - 1, _lastColumnWithDataChunkRead));
  3378. }
  3379. }
  3380. private void CheckDataIsReady(int columnIndex, bool allowPartiallyReadColumn = false, bool permitAsync = false, string methodName = null) {
  3381. if (_isClosed) {
  3382. throw ADP.DataReaderClosed(methodName ?? "CheckDataIsReady");
  3383. }
  3384. if ((!permitAsync) && (_currentTask != null)) {
  3385. throw ADP.AsyncOperationPending();
  3386. }
  3387. Debug.Assert(!_sharedState._dataReady || _metaData != null, "Data is ready, but there is no metadata?");
  3388. if ((!_sharedState._dataReady) || (_metaData == null)) {
  3389. throw SQL.InvalidRead();
  3390. }
  3391. if ((columnIndex < 0) || (columnIndex >= _metaData.Length)) {
  3392. throw ADP.IndexOutOfRange();
  3393. }
  3394. if ((IsCommandBehavior(CommandBehavior.SequentialAccess)) && // Only for sequential access
  3395. ((_sharedState._nextColumnDataToRead > columnIndex) || (_lastColumnWithDataChunkRead > columnIndex) || // Read past column
  3396. ((!allowPartiallyReadColumn) && (_lastColumnWithDataChunkRead == columnIndex)) || // Partially read column
  3397. ((allowPartiallyReadColumn) && (HasActiveStreamOrTextReaderOnColumn(columnIndex))))) { // Has a Stream or TextReader on a partially-read column
  3398. throw ADP.NonSequentialColumnAccess(columnIndex, Math.Max(_sharedState._nextColumnDataToRead, _lastColumnWithDataChunkRead + 1));
  3399. }
  3400. }
  3401. [Conditional("DEBUG")]
  3402. private void AssertReaderState(bool requireData, bool permitAsync, int? columnIndex = null, bool enforceSequentialAccess = false) {
  3403. Debug.Assert(!_sharedState._dataReady || _metaData != null, "Data is ready, but there is no metadata?");
  3404. Debug.Assert(permitAsync || _currentTask == null, "Call while async operation is pending");
  3405. Debug.Assert(_metaData != null, "_metaData is null, check MetaData before calling this method");
  3406. Debug.Assert(!requireData || _sharedState._dataReady, "No data is ready to be read");
  3407. if (columnIndex.HasValue) {
  3408. Debug.Assert(columnIndex.Value >= 0 && columnIndex.Value < _metaData.Length, "Invalid column index");
  3409. Debug.Assert((!enforceSequentialAccess) || (!IsCommandBehavior(CommandBehavior.SequentialAccess)) || ((_sharedState._nextColumnDataToRead <= columnIndex) && (_lastColumnWithDataChunkRead <= columnIndex)), "Already read past column");
  3410. }
  3411. }
  3412. public override Task<bool> NextResultAsync(CancellationToken cancellationToken) {
  3413. IntPtr hscp;
  3414. Bid.ScopeEnter(out hscp, "<sc.SqlDataReader.NextResultAsync|API> %d#", ObjectID);
  3415. try {
  3416. TaskCompletionSource<bool> source = new TaskCompletionSource<bool>();
  3417. if (IsClosed) {
  3418. source.SetException(ADP.ExceptionWithStackTrace(ADP.DataReaderClosed("NextResultAsync")));
  3419. return source.Task;
  3420. }
  3421. IDisposable registration = null;
  3422. if (cancellationToken.CanBeCanceled) {
  3423. if (cancellationToken.IsCancellationRequested) {
  3424. source.SetCanceled();
  3425. return source.Task;
  3426. }
  3427. registration = cancellationToken.Register(_command.CancelIgnoreFailure);
  3428. }
  3429. Task original = Interlocked.CompareExchange(ref _currentTask, source.Task, null);
  3430. if (original != null) {
  3431. source.SetException(ADP.ExceptionWithStackTrace(SQL.PendingBeginXXXExists()));
  3432. return source.Task;
  3433. }
  3434. // Check if cancellation due to close is requested (this needs to be done after setting _currentTask)
  3435. if (_cancelAsyncOnCloseToken.IsCancellationRequested) {
  3436. source.SetCanceled();
  3437. _currentTask = null;
  3438. return source.Task;
  3439. }
  3440. PrepareAsyncInvocation(useSnapshot: true);
  3441. Func<Task, Task<bool>> moreFunc = null;
  3442. moreFunc = (t) => {
  3443. if (t != null) {
  3444. Bid.Trace("<sc.SqlDataReader.NextResultAsync> attempt retry %d#\n", ObjectID);
  3445. PrepareForAsyncContinuation();
  3446. }
  3447. bool more;
  3448. if (TryNextResult(out more)) {
  3449. // completed
  3450. return more ? ADP.TrueTask : ADP.FalseTask;
  3451. }
  3452. return ContinueRetryable(moreFunc);
  3453. };
  3454. return InvokeRetryable(moreFunc, source, registration);
  3455. }
  3456. finally {
  3457. Bid.ScopeLeave(ref hscp);
  3458. }
  3459. }
  3460. // NOTE: This will return null if it completed sequentially
  3461. // If this returns null, then you can use bytesRead to see how many bytes were read - otherwise bytesRead should be ignored
  3462. internal Task<int> GetBytesAsync(int i, byte[] buffer, int index, int length, int timeout, CancellationToken cancellationToken, out int bytesRead) {
  3463. AssertReaderState(requireData: true, permitAsync: true, columnIndex: i, enforceSequentialAccess: true);
  3464. Debug.Assert(IsCommandBehavior(CommandBehavior.SequentialAccess));
  3465. bytesRead = 0;
  3466. if (IsClosed) {
  3467. TaskCompletionSource<int> source = new TaskCompletionSource<int>();
  3468. source.SetException(ADP.ExceptionWithStackTrace(ADP.DataReaderClosed("GetBytesAsync")));
  3469. return source.Task;
  3470. }
  3471. if (_currentTask != null) {
  3472. TaskCompletionSource<int> source = new TaskCompletionSource<int>();
  3473. source.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
  3474. return source.Task;
  3475. }
  3476. if (cancellationToken.CanBeCanceled) {
  3477. if (cancellationToken.IsCancellationRequested) {
  3478. return null;
  3479. }
  3480. }
  3481. // Check if we need to skip columns
  3482. Debug.Assert(_sharedState._nextColumnDataToRead <= _lastColumnWithDataChunkRead, "Non sequential access");
  3483. if ((_sharedState._nextColumnHeaderToRead <= _lastColumnWithDataChunkRead) || (_sharedState._nextColumnDataToRead < _lastColumnWithDataChunkRead)) {
  3484. TaskCompletionSource<int> source = new TaskCompletionSource<int>();
  3485. Task original = Interlocked.CompareExchange(ref _currentTask, source.Task, null);
  3486. if (original != null) {
  3487. source.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
  3488. return source.Task;
  3489. }
  3490. PrepareAsyncInvocation(useSnapshot: true);
  3491. Func<Task, Task<int>> moreFunc = null;
  3492. // Timeout
  3493. CancellationToken timeoutToken = CancellationToken.None;
  3494. CancellationTokenSource timeoutCancellationSource = null;
  3495. if (timeout > 0) {
  3496. timeoutCancellationSource = new CancellationTokenSource();
  3497. timeoutCancellationSource.CancelAfter(timeout);
  3498. timeoutToken = timeoutCancellationSource.Token;
  3499. }
  3500. moreFunc = (t) => {
  3501. if (t != null) {
  3502. Bid.Trace("<sc.SqlDataReader.GetBytesAsync> attempt retry %d#\n", ObjectID);
  3503. PrepareForAsyncContinuation();
  3504. }
  3505. // Prepare for stateObj timeout
  3506. SetTimeout(_defaultTimeoutMilliseconds);
  3507. if (TryReadColumnHeader(i)) {
  3508. // Only once we have read upto where we need to be can we check the cancellation tokens (otherwise we will be in an unknown state)
  3509. if (cancellationToken.IsCancellationRequested) {
  3510. // User requested cancellation
  3511. return ADP.CreatedTaskWithCancellation<int>();
  3512. }
  3513. else if (timeoutToken.IsCancellationRequested) {
  3514. // Timeout
  3515. return ADP.CreatedTaskWithException<int>(ADP.ExceptionWithStackTrace(ADP.IO(SQLMessage.Timeout())));
  3516. }
  3517. else {
  3518. // Upto the correct column - continue to read
  3519. SwitchToAsyncWithoutSnapshot();
  3520. int totalBytesRead;
  3521. var readTask = GetBytesAsyncReadDataStage(i, buffer, index, length, timeout, true, cancellationToken, timeoutToken, out totalBytesRead);
  3522. if (readTask == null) {
  3523. // Completed synchronously
  3524. return Task.FromResult<int>(totalBytesRead);
  3525. }
  3526. else {
  3527. return readTask;
  3528. }
  3529. }
  3530. }
  3531. else {
  3532. return ContinueRetryable(moreFunc);
  3533. }
  3534. };
  3535. return InvokeRetryable(moreFunc, source, timeoutCancellationSource);
  3536. }
  3537. else {
  3538. // We're already at the correct column, just read the data
  3539. // Switch to async
  3540. PrepareAsyncInvocation(useSnapshot: false);
  3541. try {
  3542. return GetBytesAsyncReadDataStage(i, buffer, index, length, timeout, false, cancellationToken, CancellationToken.None, out bytesRead);
  3543. }
  3544. catch {
  3545. CleanupAfterAsyncInvocation();
  3546. throw;
  3547. }
  3548. }
  3549. }
  3550. private Task<int> GetBytesAsyncReadDataStage(int i, byte[] buffer, int index, int length, int timeout, bool isContinuation, CancellationToken cancellationToken, CancellationToken timeoutToken, out int bytesRead) {
  3551. _lastColumnWithDataChunkRead = i;
  3552. TaskCompletionSource<int> source = null;
  3553. CancellationTokenSource timeoutCancellationSource = null;
  3554. // Prepare for stateObj timeout
  3555. SetTimeout(_defaultTimeoutMilliseconds);
  3556. // Try to read without any continuations (all the data may already be in the stateObj's buffer)
  3557. if (!TryGetBytesInternalSequential(i, buffer, index, length, out bytesRead)) {
  3558. // This will be the 'state' for the callback
  3559. int totalBytesRead = bytesRead;
  3560. if (!isContinuation) {
  3561. // This is the first async operation which is happening - setup the _currentTask and timeout
  3562. source = new TaskCompletionSource<int>();
  3563. Task original = Interlocked.CompareExchange(ref _currentTask, source.Task, null);
  3564. if (original != null) {
  3565. source.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
  3566. return source.Task;
  3567. }
  3568. // Check if cancellation due to close is requested (this needs to be done after setting _currentTask)
  3569. if (_cancelAsyncOnCloseToken.IsCancellationRequested) {
  3570. source.SetCanceled();
  3571. _currentTask = null;
  3572. return source.Task;
  3573. }
  3574. // Timeout
  3575. Debug.Assert(timeoutToken == CancellationToken.None, "TimeoutToken is set when GetBytesAsyncReadDataStage is not a continuation");
  3576. if (timeout > 0) {
  3577. timeoutCancellationSource = new CancellationTokenSource();
  3578. timeoutCancellationSource.CancelAfter(timeout);
  3579. timeoutToken = timeoutCancellationSource.Token;
  3580. }
  3581. }
  3582. Func<Task, Task<int>> moreFunc = null;
  3583. moreFunc = (_ => {
  3584. PrepareForAsyncContinuation();
  3585. if (cancellationToken.IsCancellationRequested) {
  3586. // User requested cancellation
  3587. return ADP.CreatedTaskWithCancellation<int>();
  3588. }
  3589. else if (timeoutToken.IsCancellationRequested) {
  3590. // Timeout
  3591. return ADP.CreatedTaskWithException<int>(ADP.ExceptionWithStackTrace(ADP.IO(SQLMessage.Timeout())));
  3592. }
  3593. else {
  3594. // Prepare for stateObj timeout
  3595. SetTimeout(_defaultTimeoutMilliseconds);
  3596. int bytesReadThisIteration;
  3597. bool result = TryGetBytesInternalSequential(i, buffer, index + totalBytesRead, length - totalBytesRead, out bytesReadThisIteration);
  3598. totalBytesRead += bytesReadThisIteration;
  3599. Debug.Assert(totalBytesRead <= length, "Read more bytes than required");
  3600. if (result) {
  3601. return Task.FromResult<int>(totalBytesRead);
  3602. }
  3603. else {
  3604. return ContinueRetryable(moreFunc);
  3605. }
  3606. }
  3607. });
  3608. Task<int> retryTask = ContinueRetryable(moreFunc);
  3609. if (isContinuation) {
  3610. // Let the caller handle cleanup\completing
  3611. return retryTask;
  3612. }
  3613. else {
  3614. // setup for cleanup\completing
  3615. retryTask.ContinueWith((t) => CompleteRetryable(t, source, timeoutCancellationSource), TaskScheduler.Default);
  3616. return source.Task;
  3617. }
  3618. }
  3619. if (!isContinuation) {
  3620. // If this is the first async op, we need to cleanup
  3621. CleanupAfterAsyncInvocation();
  3622. }
  3623. // Completed synchronously, return null
  3624. return null;
  3625. }
  3626. public override Task<bool> ReadAsync(CancellationToken cancellationToken) {
  3627. IntPtr hscp;
  3628. Bid.ScopeEnter(out hscp, "<sc.SqlDataReader.ReadAsync|API> %d#", ObjectID);
  3629. try {
  3630. if (IsClosed) {
  3631. return ADP.CreatedTaskWithException<bool>(ADP.ExceptionWithStackTrace(ADP.DataReaderClosed("ReadAsync")));
  3632. }
  3633. // If user's token is canceled, return a canceled task
  3634. if (cancellationToken.IsCancellationRequested) {
  3635. return ADP.CreatedTaskWithCancellation<bool>();
  3636. }
  3637. // Check for existing async
  3638. if (_currentTask != null) {
  3639. return ADP.CreatedTaskWithException<bool>(ADP.ExceptionWithStackTrace(SQL.PendingBeginXXXExists()));
  3640. }
  3641. // These variables will be captured in moreFunc so that we can skip searching for a row token once one has been read
  3642. bool rowTokenRead = false;
  3643. bool more = false;
  3644. // Shortcut, do we have enough data to immediately do the ReadAsync?
  3645. try {
  3646. // First, check if we can finish reading the current row
  3647. // NOTE: If we are in SingleRow mode and we've read that single row (i.e. _haltRead == true), then skip the shortcut
  3648. if ((!_haltRead) && ((!_sharedState._dataReady) || (WillHaveEnoughData(_metaData.Length - 1)))) {
  3649. #if DEBUG
  3650. try {
  3651. _stateObj._shouldHaveEnoughData = true;
  3652. #endif
  3653. if (_sharedState._dataReady) {
  3654. // Clean off current row
  3655. CleanPartialReadReliable();
  3656. }
  3657. // If there a ROW token ready (as well as any metadata for the row)
  3658. if (_stateObj.IsRowTokenReady()) {
  3659. // Read the ROW token
  3660. bool result = TryReadInternal(true, out more);
  3661. Debug.Assert(result, "Should not have run out of data");
  3662. rowTokenRead = true;
  3663. if (more) {
  3664. // Sequential mode, nothing left to do
  3665. if (IsCommandBehavior(CommandBehavior.SequentialAccess)) {
  3666. return ADP.TrueTask;
  3667. }
  3668. // For non-sequential, check if we can read the row data now
  3669. else if (WillHaveEnoughData(_metaData.Length - 1)) {
  3670. // Read row data
  3671. result = TryReadColumn(_metaData.Length - 1, setTimeout: true);
  3672. Debug.Assert(result, "Should not have run out of data");
  3673. return ADP.TrueTask;
  3674. }
  3675. }
  3676. else {
  3677. // No data left, return
  3678. return ADP.FalseTask;
  3679. }
  3680. }
  3681. #if DEBUG
  3682. }
  3683. finally {
  3684. _stateObj._shouldHaveEnoughData = false;
  3685. }
  3686. #endif
  3687. }
  3688. }
  3689. catch (Exception ex) {
  3690. if (!ADP.IsCatchableExceptionType(ex)) {
  3691. throw;
  3692. }
  3693. return ADP.CreatedTaskWithException<bool>(ex);
  3694. }
  3695. TaskCompletionSource<bool> source = new TaskCompletionSource<bool>();
  3696. Task original = Interlocked.CompareExchange(ref _currentTask, source.Task, null);
  3697. if (original != null) {
  3698. source.SetException(ADP.ExceptionWithStackTrace(SQL.PendingBeginXXXExists()));
  3699. return source.Task;
  3700. }
  3701. // Check if cancellation due to close is requested (this needs to be done after setting _currentTask)
  3702. if (_cancelAsyncOnCloseToken.IsCancellationRequested) {
  3703. source.SetCanceled();
  3704. _currentTask = null;
  3705. return source.Task;
  3706. }
  3707. IDisposable registration = null;
  3708. if (cancellationToken.CanBeCanceled) {
  3709. registration = cancellationToken.Register(_command.CancelIgnoreFailure);
  3710. }
  3711. PrepareAsyncInvocation(useSnapshot: true);
  3712. Func<Task, Task<bool>> moreFunc = null;
  3713. moreFunc = (t) => {
  3714. if (t != null) {
  3715. Bid.Trace("<sc.SqlDataReader.ReadAsync> attempt retry %d#\n", ObjectID);
  3716. PrepareForAsyncContinuation();
  3717. }
  3718. if (rowTokenRead || TryReadInternal(true, out more)) {
  3719. // If there are no more rows, or this is Sequential Access, then we are done
  3720. if (!more || (_commandBehavior & CommandBehavior.SequentialAccess) == CommandBehavior.SequentialAccess) {
  3721. // completed
  3722. return more ? ADP.TrueTask : ADP.FalseTask;
  3723. }
  3724. else {
  3725. // First time reading the row token - update the snapshot
  3726. if (!rowTokenRead) {
  3727. rowTokenRead = true;
  3728. _snapshot = null;
  3729. PrepareAsyncInvocation(useSnapshot: true);
  3730. }
  3731. // if non-sequentialaccess then read entire row before returning
  3732. if (TryReadColumn(_metaData.Length - 1, true)) {
  3733. // completed
  3734. return ADP.TrueTask;
  3735. }
  3736. }
  3737. }
  3738. return ContinueRetryable(moreFunc);
  3739. };
  3740. return InvokeRetryable(moreFunc, source, registration);
  3741. }
  3742. finally {
  3743. Bid.ScopeLeave(ref hscp);
  3744. }
  3745. }
  3746. override public Task<bool> IsDBNullAsync(int i, CancellationToken cancellationToken) {
  3747. try {
  3748. CheckHeaderIsReady(columnIndex: i, methodName: "IsDBNullAsync");
  3749. }
  3750. catch (Exception ex) {
  3751. if (!ADP.IsCatchableExceptionType(ex)) {
  3752. throw;
  3753. }
  3754. return ADP.CreatedTaskWithException<bool>(ex);
  3755. }
  3756. // Shortcut - if there are no issues and the data is already read, then just return the value
  3757. if ((_sharedState._nextColumnHeaderToRead > i) && (!cancellationToken.IsCancellationRequested) && (_currentTask == null)) {
  3758. var data = _data;
  3759. if (data != null) {
  3760. return data[i].IsNull ? ADP.TrueTask : ADP.FalseTask;
  3761. }
  3762. else {
  3763. // Reader was closed between the CheckHeaderIsReady and accessing _data - throw closed exception
  3764. return ADP.CreatedTaskWithException<bool>(ADP.ExceptionWithStackTrace(ADP.DataReaderClosed("IsDBNullAsync")));
  3765. }
  3766. }
  3767. else {
  3768. // Throw if there is any current task
  3769. if (_currentTask != null) {
  3770. return ADP.CreatedTaskWithException<bool>(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
  3771. }
  3772. // If user's token is canceled, return a canceled task
  3773. if (cancellationToken.IsCancellationRequested) {
  3774. return ADP.CreatedTaskWithCancellation<bool>();
  3775. }
  3776. // Shortcut - if we have enough data, then run [....]
  3777. try {
  3778. if (WillHaveEnoughData(i, headerOnly: true)) {
  3779. #if DEBUG
  3780. try {
  3781. _stateObj._shouldHaveEnoughData = true;
  3782. #endif
  3783. ReadColumnHeader(i);
  3784. return _data[i].IsNull ? ADP.TrueTask : ADP.FalseTask;
  3785. #if DEBUG
  3786. }
  3787. finally {
  3788. _stateObj._shouldHaveEnoughData = false;
  3789. }
  3790. #endif
  3791. }
  3792. }
  3793. catch (Exception ex) {
  3794. if (!ADP.IsCatchableExceptionType(ex)) {
  3795. throw;
  3796. }
  3797. return ADP.CreatedTaskWithException<bool>(ex);
  3798. }
  3799. // Setup and check for pending task
  3800. TaskCompletionSource<bool> source = new TaskCompletionSource<bool>();
  3801. Task original = Interlocked.CompareExchange(ref _currentTask, source.Task, null);
  3802. if (original != null) {
  3803. source.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
  3804. return source.Task;
  3805. }
  3806. // Check if cancellation due to close is requested (this needs to be done after setting _currentTask)
  3807. if (_cancelAsyncOnCloseToken.IsCancellationRequested) {
  3808. source.SetCanceled();
  3809. _currentTask = null;
  3810. return source.Task;
  3811. }
  3812. // Setup cancellations
  3813. IDisposable registration = null;
  3814. if (cancellationToken.CanBeCanceled) {
  3815. registration = cancellationToken.Register(_command.CancelIgnoreFailure);
  3816. }
  3817. // Setup async
  3818. PrepareAsyncInvocation(useSnapshot: true);
  3819. // Setup the retryable function
  3820. Func<Task, Task<bool>> moreFunc = null;
  3821. moreFunc = (t) => {
  3822. if (t != null) {
  3823. PrepareForAsyncContinuation();
  3824. }
  3825. if (TryReadColumnHeader(i)) {
  3826. return _data[i].IsNull ? ADP.TrueTask : ADP.FalseTask;
  3827. }
  3828. else {
  3829. return ContinueRetryable(moreFunc);
  3830. }
  3831. };
  3832. // Go!
  3833. return InvokeRetryable(moreFunc, source, registration);
  3834. }
  3835. }
  3836. override public Task<T> GetFieldValueAsync<T>(int i, CancellationToken cancellationToken) {
  3837. try {
  3838. CheckDataIsReady(columnIndex: i, methodName: "GetFieldValueAsync");
  3839. // Shortcut - if there are no issues and the data is already read, then just return the value
  3840. if ((!IsCommandBehavior(CommandBehavior.SequentialAccess)) && (_sharedState._nextColumnDataToRead > i) && (!cancellationToken.IsCancellationRequested) && (_currentTask == null)) {
  3841. var data = _data;
  3842. var metaData =_metaData;
  3843. if ((data != null) && (metaData != null)) {
  3844. return Task.FromResult<T>(GetFieldValueFromSqlBufferInternal<T>(data[i], metaData[i]));
  3845. }
  3846. else {
  3847. // Reader was closed between the CheckDataIsReady and accessing _data\_metaData - throw closed exception
  3848. return ADP.CreatedTaskWithException<T>(ADP.ExceptionWithStackTrace(ADP.DataReaderClosed("GetFieldValueAsync")));
  3849. }
  3850. }
  3851. } catch (Exception ex) {
  3852. if (!ADP.IsCatchableExceptionType(ex)) {
  3853. throw;
  3854. }
  3855. return ADP.CreatedTaskWithException<T>(ex);
  3856. }
  3857. // Throw if there is any current task
  3858. if (_currentTask != null) {
  3859. return ADP.CreatedTaskWithException<T>(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
  3860. }
  3861. // If user's token is canceled, return a canceled task
  3862. if (cancellationToken.IsCancellationRequested) {
  3863. return ADP.CreatedTaskWithCancellation<T>();
  3864. }
  3865. // Shortcut - if we have enough data, then run [....]
  3866. try {
  3867. if (WillHaveEnoughData(i)) {
  3868. #if DEBUG
  3869. try {
  3870. _stateObj._shouldHaveEnoughData = true;
  3871. #endif
  3872. return Task.FromResult(GetFieldValueInternal<T>(i));
  3873. #if DEBUG
  3874. }
  3875. finally {
  3876. _stateObj._shouldHaveEnoughData = false;
  3877. }
  3878. #endif
  3879. }
  3880. }
  3881. catch (Exception ex) {
  3882. if (!ADP.IsCatchableExceptionType(ex)) {
  3883. throw;
  3884. }
  3885. return ADP.CreatedTaskWithException<T>(ex);
  3886. }
  3887. // Setup and check for pending task
  3888. TaskCompletionSource<T> source = new TaskCompletionSource<T>();
  3889. Task original = Interlocked.CompareExchange(ref _currentTask, source.Task, null);
  3890. if (original != null) {
  3891. source.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
  3892. return source.Task;
  3893. }
  3894. // Check if cancellation due to close is requested (this needs to be done after setting _currentTask)
  3895. if (_cancelAsyncOnCloseToken.IsCancellationRequested) {
  3896. source.SetCanceled();
  3897. _currentTask = null;
  3898. return source.Task;
  3899. }
  3900. // Setup cancellations
  3901. IDisposable registration = null;
  3902. if (cancellationToken.CanBeCanceled) {
  3903. registration = cancellationToken.Register(_command.CancelIgnoreFailure);
  3904. }
  3905. // Setup async
  3906. PrepareAsyncInvocation(useSnapshot: true);
  3907. // Setup the retryable function
  3908. Func<Task, Task<T>> moreFunc = null;
  3909. moreFunc = (t) => {
  3910. if (t != null) {
  3911. PrepareForAsyncContinuation();
  3912. }
  3913. if (TryReadColumn(i, setTimeout: false)) {
  3914. return Task.FromResult<T>(GetFieldValueFromSqlBufferInternal<T>(_data[i], _metaData[i]));
  3915. }
  3916. else {
  3917. return ContinueRetryable(moreFunc);
  3918. }
  3919. };
  3920. // Go!
  3921. return InvokeRetryable(moreFunc, source, registration);
  3922. }
  3923. #if DEBUG
  3924. internal void CompletePendingReadWithSuccess(bool resetForcePendingReadsToWait) {
  3925. var stateObj = _stateObj;
  3926. if (stateObj != null) {
  3927. stateObj.CompletePendingReadWithSuccess(resetForcePendingReadsToWait);
  3928. }
  3929. }
  3930. internal void CompletePendingReadWithFailure(int errorCode, bool resetForcePendingReadsToWait) {
  3931. var stateObj = _stateObj;
  3932. if (stateObj != null) {
  3933. stateObj.CompletePendingReadWithFailure(errorCode, resetForcePendingReadsToWait);
  3934. }
  3935. }
  3936. #endif
  3937. class Snapshot {
  3938. public bool _dataReady;
  3939. public bool _haltRead;
  3940. public bool _metaDataConsumed;
  3941. public bool _browseModeInfoConsumed;
  3942. public bool _hasRows;
  3943. public ALTROWSTATUS _altRowStatus;
  3944. public int _nextColumnDataToRead;
  3945. public int _nextColumnHeaderToRead;
  3946. public long _columnDataBytesRead;
  3947. public long _columnDataBytesRemaining;
  3948. public _SqlMetaDataSet _metadata;
  3949. public _SqlMetaDataSetCollection _altMetaDataSetCollection;
  3950. public MultiPartTableName[] _tableNames;
  3951. public SqlSequentialStream _currentStream;
  3952. public SqlSequentialTextReader _currentTextReader;
  3953. }
  3954. private Task<T> ContinueRetryable<T>(Func<Task, Task<T>> moreFunc) {
  3955. // _networkPacketTaskSource could be null if the connection was closed
  3956. // while an async invocation was outstanding.
  3957. TaskCompletionSource<object> completionSource = _stateObj._networkPacketTaskSource;
  3958. if (_cancelAsyncOnCloseToken.IsCancellationRequested || completionSource == null) {
  3959. // Cancellation requested due to datareader being closed
  3960. TaskCompletionSource<T> source = new TaskCompletionSource<T>();
  3961. source.TrySetException(ADP.ExceptionWithStackTrace(ADP.ClosedConnectionError()));
  3962. return source.Task;
  3963. }
  3964. else {
  3965. return completionSource.Task.ContinueWith((retryTask) => {
  3966. if (retryTask.IsFaulted) {
  3967. // Somehow the network task faulted - return the exception
  3968. TaskCompletionSource<T> exceptionSource = new TaskCompletionSource<T>();
  3969. exceptionSource.TrySetException(retryTask.Exception.InnerException);
  3970. return exceptionSource.Task;
  3971. }
  3972. else if (!_cancelAsyncOnCloseToken.IsCancellationRequested) {
  3973. TdsParserStateObject stateObj = _stateObj;
  3974. if (stateObj != null) {
  3975. // protect continuations against concurrent
  3976. // close and cancel
  3977. lock (stateObj) {
  3978. if (_stateObj != null) { // reader not closed while we waited for the lock
  3979. if (retryTask.IsCanceled) {
  3980. if (_parser != null) {
  3981. _parser.State = TdsParserState.Broken; // We failed to respond to attention, we have to quit!
  3982. _parser.Connection.BreakConnection();
  3983. _parser.ThrowExceptionAndWarning(_stateObj);
  3984. }
  3985. }
  3986. else {
  3987. if (!IsClosed) {
  3988. try {
  3989. return moreFunc(retryTask);
  3990. }
  3991. catch (Exception) {
  3992. CleanupAfterAsyncInvocation();
  3993. throw;
  3994. }
  3995. }
  3996. }
  3997. }
  3998. }
  3999. }
  4000. }
  4001. // if stateObj is null, or we closed the connection or the connection was already closed,
  4002. // then mark this operation as cancelled.
  4003. TaskCompletionSource<T> source = new TaskCompletionSource<T>();
  4004. source.SetException(ADP.ExceptionWithStackTrace(ADP.ClosedConnectionError()));
  4005. return source.Task;
  4006. }, TaskScheduler.Default).Unwrap();
  4007. }
  4008. }
  4009. private Task<T> InvokeRetryable<T>(Func<Task, Task<T>> moreFunc, TaskCompletionSource<T> source, IDisposable objectToDispose = null) {
  4010. try {
  4011. Task<T> task;
  4012. try {
  4013. task = moreFunc(null);
  4014. }
  4015. catch (Exception ex) {
  4016. task = ADP.CreatedTaskWithException<T>(ex);
  4017. }
  4018. if (task.IsCompleted) {
  4019. // If we've completed [....], then don't bother handling the TaskCompletionSource - we'll just return the completed task
  4020. CompleteRetryable(task, source, objectToDispose);
  4021. return task;
  4022. }
  4023. else {
  4024. task.ContinueWith((t) => CompleteRetryable(t, source, objectToDispose), TaskScheduler.Default);
  4025. }
  4026. }
  4027. catch (AggregateException e) {
  4028. source.TrySetException(e.InnerException);
  4029. }
  4030. catch (Exception e) {
  4031. source.TrySetException(e);
  4032. }
  4033. // Fall through for exceptions\completing async
  4034. return source.Task;
  4035. }
  4036. private void CompleteRetryable<T>(Task<T> task, TaskCompletionSource<T> source, IDisposable objectToDispose) {
  4037. if (objectToDispose != null) {
  4038. objectToDispose.Dispose();
  4039. }
  4040. // If something has forced us to switch to SyncOverAsync mode while in an async task then we need to guarantee that we do the cleanup
  4041. // This avoids us replaying non-replayable data (such as DONE or ENV_CHANGE tokens)
  4042. var stateObj = _stateObj;
  4043. bool ignoreCloseToken = ((stateObj != null) && (stateObj._syncOverAsync));
  4044. CleanupAfterAsyncInvocation(ignoreCloseToken);
  4045. Task current = Interlocked.CompareExchange(ref _currentTask, null, source.Task);
  4046. Debug.Assert(current == source.Task, "Should not be able to change the _currentTask while an asynchronous operation is pending");
  4047. if (task.IsFaulted) {
  4048. Exception e = task.Exception.InnerException;
  4049. source.TrySetException(e);
  4050. }
  4051. else if (task.IsCanceled) {
  4052. source.TrySetCanceled();
  4053. }
  4054. else {
  4055. source.TrySetResult(task.Result);
  4056. }
  4057. }
  4058. private void PrepareAsyncInvocation(bool useSnapshot) {
  4059. // if there is already a snapshot, then the previous async command
  4060. // completed with exception or cancellation. We need to continue
  4061. // with the old snapshot.
  4062. if (useSnapshot) {
  4063. Debug.Assert(!_stateObj._asyncReadWithoutSnapshot, "Can't prepare async invocation with snapshot if doing async without snapshots");
  4064. if (_snapshot == null) {
  4065. _snapshot = new Snapshot {
  4066. _dataReady = _sharedState._dataReady,
  4067. _haltRead = _haltRead,
  4068. _metaDataConsumed = _metaDataConsumed,
  4069. _browseModeInfoConsumed = _browseModeInfoConsumed,
  4070. _hasRows = _hasRows,
  4071. _altRowStatus = _altRowStatus,
  4072. _nextColumnDataToRead = _sharedState._nextColumnDataToRead,
  4073. _nextColumnHeaderToRead = _sharedState._nextColumnHeaderToRead,
  4074. _columnDataBytesRead = _columnDataBytesRead,
  4075. _columnDataBytesRemaining = _sharedState._columnDataBytesRemaining,
  4076. // _metadata and _altaMetaDataSetCollection must be Cloned
  4077. // before they are updated
  4078. _metadata = _metaData,
  4079. _altMetaDataSetCollection = _altMetaDataSetCollection,
  4080. _tableNames = _tableNames,
  4081. _currentStream = _currentStream,
  4082. _currentTextReader = _currentTextReader,
  4083. };
  4084. _stateObj.SetSnapshot();
  4085. }
  4086. }
  4087. else {
  4088. Debug.Assert(_snapshot == null, "Can prepare async invocation without snapshot if there is currently a snapshot");
  4089. _stateObj._asyncReadWithoutSnapshot = true;
  4090. }
  4091. _stateObj._syncOverAsync = false;
  4092. _stateObj._executionContext = ExecutionContext.Capture();
  4093. }
  4094. private void CleanupAfterAsyncInvocation(bool ignoreCloseToken = false) {
  4095. var stateObj = _stateObj;
  4096. if (stateObj != null) {
  4097. // If close requested cancellation and we have a snapshot, then it will deal with cleaning up
  4098. // NOTE: There are some cases where we wish to ignore the close token, such as when we've read some data that is not replayable (e.g. DONE or ENV_CHANGE token)
  4099. if ((ignoreCloseToken) || (!_cancelAsyncOnCloseToken.IsCancellationRequested) || (stateObj._asyncReadWithoutSnapshot)) {
  4100. // Prevent race condition between the DataReader being closed (e.g. when another MARS thread has an error)
  4101. lock(stateObj) {
  4102. if (_stateObj != null) { // reader not closed while we waited for the lock
  4103. CleanupAfterAsyncInvocationInternal(_stateObj);
  4104. Debug.Assert(_snapshot == null && !_stateObj._asyncReadWithoutSnapshot, "Snapshot not null or async without snapshot still enabled after cleaning async state");
  4105. }
  4106. }
  4107. }
  4108. }
  4109. }
  4110. // This function is called directly if calling function already closed the reader, so _stateObj is null,
  4111. // in other cases parameterless version should be called
  4112. private void CleanupAfterAsyncInvocationInternal(TdsParserStateObject stateObj, bool resetNetworkPacketTaskSource = true)
  4113. {
  4114. if (resetNetworkPacketTaskSource) {
  4115. stateObj._networkPacketTaskSource = null;
  4116. }
  4117. stateObj.ResetSnapshot();
  4118. stateObj._syncOverAsync = true;
  4119. stateObj._executionContext = null;
  4120. stateObj._asyncReadWithoutSnapshot = false;
  4121. #if DEBUG
  4122. stateObj._permitReplayStackTraceToDiffer = false;
  4123. #endif
  4124. // We are setting this to null inside the if-statement because stateObj==null means that the reader hasn't been initialized or has been closed (either way _snapshot should already be null)
  4125. _snapshot = null;
  4126. }
  4127. private void PrepareForAsyncContinuation() {
  4128. Debug.Assert(((_snapshot != null) || (_stateObj._asyncReadWithoutSnapshot)), "Can not prepare for an async continuation if no async if setup");
  4129. if (_snapshot != null) {
  4130. _sharedState._dataReady = _snapshot._dataReady;
  4131. _haltRead = _snapshot._haltRead;
  4132. _metaDataConsumed = _snapshot._metaDataConsumed;
  4133. _browseModeInfoConsumed = _snapshot._browseModeInfoConsumed;
  4134. _hasRows = _snapshot._hasRows;
  4135. _altRowStatus = _snapshot._altRowStatus;
  4136. _sharedState._nextColumnDataToRead = _snapshot._nextColumnDataToRead;
  4137. _sharedState._nextColumnHeaderToRead = _snapshot._nextColumnHeaderToRead;
  4138. _columnDataBytesRead = _snapshot._columnDataBytesRead;
  4139. _sharedState._columnDataBytesRemaining = _snapshot._columnDataBytesRemaining;
  4140. _metaData = _snapshot._metadata;
  4141. _altMetaDataSetCollection = _snapshot._altMetaDataSetCollection;
  4142. _tableNames = _snapshot._tableNames;
  4143. _currentStream = _snapshot._currentStream;
  4144. _currentTextReader = _snapshot._currentTextReader;
  4145. _stateObj.PrepareReplaySnapshot();
  4146. }
  4147. _stateObj._executionContext = ExecutionContext.Capture();
  4148. }
  4149. private void SwitchToAsyncWithoutSnapshot() {
  4150. Debug.Assert(_snapshot != null, "Should currently have a snapshot");
  4151. Debug.Assert(_stateObj != null && !_stateObj._asyncReadWithoutSnapshot, "Already in async without snapshot");
  4152. _snapshot = null;
  4153. _stateObj.ResetSnapshot();
  4154. _stateObj._asyncReadWithoutSnapshot = true;
  4155. }
  4156. }// SqlDataReader
  4157. }// namespace