SqlConnection.cs 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754
  1. //
  2. // System.Data.SqlClient.SqlConnection.cs
  3. //
  4. // Authors:
  5. // Rodrigo Moya ([email protected])
  6. // Daniel Morgan ([email protected])
  7. // Tim Coleman ([email protected])
  8. // Phillip Jerkins ([email protected])
  9. // Diego Caravana ([email protected])
  10. //
  11. // Copyright (C) Ximian, Inc 2002
  12. // Copyright (C) Daniel Morgan 2002, 2003
  13. // Copyright (C) Tim Coleman, 2002, 2003
  14. // Copyright (C) Phillip Jerkins, 2003
  15. //
  16. //
  17. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  18. //
  19. // Permission is hereby granted, free of charge, to any person obtaining
  20. // a copy of this software and associated documentation files (the
  21. // "Software"), to deal in the Software without restriction, including
  22. // without limitation the rights to use, copy, modify, merge, publish,
  23. // distribute, sublicense, and/or sell copies of the Software, and to
  24. // permit persons to whom the Software is furnished to do so, subject to
  25. // the following conditions:
  26. //
  27. // The above copyright notice and this permission notice shall be
  28. // included in all copies or substantial portions of the Software.
  29. //
  30. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  31. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  32. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  33. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  34. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  35. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  36. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  37. //
  38. using Mono.Data.Tds;
  39. using Mono.Data.Tds.Protocol;
  40. using System;
  41. using System.Collections;
  42. using System.Collections.Specialized;
  43. using System.ComponentModel;
  44. using System.Data;
  45. using System.Data.Common;
  46. #if !MOBILE
  47. using System.EnterpriseServices;
  48. #endif
  49. using System.Globalization;
  50. using System.Net;
  51. using System.Net.Sockets;
  52. using System.Text;
  53. using System.Xml;
  54. #if NET_2_0
  55. using System.Collections.Generic;
  56. #endif
  57. namespace System.Data.SqlClient
  58. {
  59. [DefaultEvent ("InfoMessage")]
  60. #if NET_2_0
  61. public sealed class SqlConnection : DbConnection, IDbConnection, ICloneable
  62. #else
  63. public sealed class SqlConnection : Component, IDbConnection, ICloneable
  64. #endif // NET_2_0
  65. {
  66. #region Fields
  67. bool disposed;
  68. // The set of SQL connection pools
  69. static TdsConnectionPoolManager sqlConnectionPools = new TdsConnectionPoolManager (TdsVersion.tds80);
  70. #if NET_2_0
  71. const int DEFAULT_PACKETSIZE = 8000;
  72. const int MAX_PACKETSIZE = 32768;
  73. #else
  74. const int DEFAULT_PACKETSIZE = 8192;
  75. const int MAX_PACKETSIZE = 32767;
  76. #endif
  77. const int MIN_PACKETSIZE = 512;
  78. const int DEFAULT_CONNECTIONTIMEOUT = 15;
  79. const int DEFAULT_CONNECTIONLIFETIME = 0;
  80. const int DEFAULT_MAXPOOLSIZE = 100;
  81. const int MIN_MAXPOOLSIZE = 1;
  82. const int DEFAULT_MINPOOLSIZE = 0;
  83. const int DEFAULT_PORT = 1433;
  84. // The current connection pool
  85. TdsConnectionPool pool;
  86. // The connection string that identifies this connection
  87. string connectionString;
  88. // The transaction object for the current transaction
  89. SqlTransaction transaction;
  90. // Connection parameters
  91. TdsConnectionParameters parms;
  92. bool connectionReset;
  93. int connectionLifeTime;
  94. bool pooling;
  95. string dataSource;
  96. int connectionTimeout;
  97. int minPoolSize;
  98. int maxPoolSize;
  99. int packetSize;
  100. int port;
  101. bool fireInfoMessageEventOnUserErrors;
  102. bool statisticsEnabled;
  103. // The current state
  104. ConnectionState state = ConnectionState.Closed;
  105. SqlDataReader dataReader;
  106. XmlReader xmlReader;
  107. // The TDS object
  108. Tds tds;
  109. #endregion // Fields
  110. #region Constructors
  111. public SqlConnection () : this (null)
  112. {
  113. }
  114. public SqlConnection (string connectionString)
  115. {
  116. ConnectionString = connectionString;
  117. }
  118. #endregion // Constructors
  119. #region Properties
  120. [DefaultValue ("")]
  121. [EditorAttribute ("Microsoft.VSDesigner.Data.SQL.Design.SqlConnectionStringEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  122. [RecommendedAsConfigurable (true)]
  123. [RefreshProperties (RefreshProperties.All)]
  124. public override string ConnectionString {
  125. get {
  126. if (connectionString == null)
  127. return string.Empty;
  128. return connectionString;
  129. }
  130. [MonoTODO("persist security info, encrypt, enlist keyword not implemented")]
  131. set {
  132. if (state == ConnectionState.Open)
  133. throw new InvalidOperationException ("Not Allowed to change ConnectionString property while Connection state is OPEN");
  134. SetConnectionString (value);
  135. }
  136. }
  137. #if !NET_2_0
  138. [DataSysDescription ("Current connection timeout value, 'Connect Timeout=X' in the ConnectionString.")]
  139. #endif
  140. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  141. public
  142. #if NET_2_0
  143. override
  144. #endif // NET_2_0
  145. int ConnectionTimeout {
  146. get { return connectionTimeout; }
  147. }
  148. #if !NET_2_0
  149. [DataSysDescription ("Current SQL Server database, 'Initial Catalog=X' in the connection string.")]
  150. #endif
  151. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  152. public
  153. #if NET_2_0
  154. override
  155. #endif // NET_2_0
  156. string Database {
  157. get {
  158. if (State == ConnectionState.Open)
  159. return tds.Database;
  160. return parms.Database ;
  161. }
  162. }
  163. internal SqlDataReader DataReader {
  164. get { return dataReader; }
  165. set { dataReader = value; }
  166. }
  167. #if !NET_2_0
  168. [DataSysDescription ("Current SqlServer that the connection is opened to, 'Data Source=X' in the connection string. ")]
  169. #else
  170. [Browsable(true)]
  171. #endif
  172. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  173. public
  174. #if NET_2_0
  175. override
  176. #endif // NET_2_0
  177. string DataSource {
  178. get { return dataSource; }
  179. }
  180. #if !NET_2_0
  181. [DataSysDescription ("Network packet size, 'Packet Size=x' in the connection string.")]
  182. #endif
  183. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  184. public int PacketSize {
  185. get {
  186. if (State == ConnectionState.Open)
  187. return ((Tds) tds).PacketSize;
  188. return packetSize;
  189. }
  190. }
  191. [Browsable (false)]
  192. #if !NET_2_0
  193. [DataSysDescription ("Version of the SQL Server accessed by the SqlConnection.")]
  194. #endif
  195. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  196. public
  197. #if NET_2_0
  198. override
  199. #endif // NET_2_0
  200. string ServerVersion {
  201. get {
  202. if (state == ConnectionState.Closed)
  203. throw ExceptionHelper.ConnectionClosed ();
  204. else
  205. return tds.ServerVersion;
  206. }
  207. }
  208. [Browsable (false)]
  209. #if !NET_2_0
  210. [DataSysDescription ("The ConnectionState indicating whether the connection is open or closed.")]
  211. #endif
  212. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  213. public
  214. #if NET_2_0
  215. override
  216. #endif // NET_2_0
  217. ConnectionState State {
  218. get { return state; }
  219. }
  220. internal Tds Tds {
  221. get { return tds; }
  222. }
  223. internal SqlTransaction Transaction {
  224. get { return transaction; }
  225. set { transaction = value; }
  226. }
  227. #if !NET_2_0
  228. [DataSysDescription ("Workstation Id, 'Workstation ID=x' in the connection string.")]
  229. #endif
  230. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  231. public string WorkstationId {
  232. get { return parms.Hostname; }
  233. }
  234. internal XmlReader XmlReader {
  235. get { return xmlReader; }
  236. set { xmlReader = value; }
  237. }
  238. #if NET_2_0
  239. public bool FireInfoMessageEventOnUserErrors {
  240. get { return fireInfoMessageEventOnUserErrors; }
  241. set { fireInfoMessageEventOnUserErrors = value; }
  242. }
  243. [DefaultValue (false)]
  244. public bool StatisticsEnabled {
  245. get { return statisticsEnabled; }
  246. set { statisticsEnabled = value; }
  247. }
  248. #endif
  249. protected internal override DbProviderFactory DbProviderFactory {
  250. get {
  251. return SqlClientFactory.Instance;
  252. }
  253. }
  254. #endregion // Properties
  255. #region Events
  256. #if !NET_2_0
  257. [DataSysDescription ("Event triggered when messages arrive from the DataSource.")]
  258. #endif
  259. public event SqlInfoMessageEventHandler InfoMessage;
  260. #if !NET_2_0
  261. [DataSysDescription ("Event triggered when the connection changes state.")]
  262. public new event StateChangeEventHandler StateChange;
  263. #endif
  264. #endregion // Events
  265. #region Delegates
  266. private void ErrorHandler (object sender, TdsInternalErrorMessageEventArgs e)
  267. {
  268. try {
  269. if (!tds.IsConnected)
  270. Close ();
  271. } catch {
  272. try {
  273. Close ();
  274. } catch {
  275. }
  276. }
  277. throw new SqlException (e.Class, e.LineNumber, e.Message, e.Number, e.Procedure, e.Server, "Mono SqlClient Data Provider", e.State);
  278. }
  279. private void MessageHandler (object sender, TdsInternalInfoMessageEventArgs e)
  280. {
  281. OnSqlInfoMessage (CreateSqlInfoMessageEvent (e.Errors));
  282. }
  283. #endregion // Delegates
  284. #region Methods
  285. public new SqlTransaction BeginTransaction ()
  286. {
  287. return BeginTransaction (IsolationLevel.ReadCommitted, String.Empty);
  288. }
  289. public new SqlTransaction BeginTransaction (IsolationLevel iso)
  290. {
  291. return BeginTransaction (iso, String.Empty);
  292. }
  293. public SqlTransaction BeginTransaction (string transactionName)
  294. {
  295. return BeginTransaction (IsolationLevel.ReadCommitted, transactionName);
  296. }
  297. public SqlTransaction BeginTransaction (IsolationLevel iso, string transactionName)
  298. {
  299. if (state == ConnectionState.Closed)
  300. throw ExceptionHelper.ConnectionClosed ();
  301. if (transaction != null)
  302. throw new InvalidOperationException ("SqlConnection does not support parallel transactions.");
  303. string isolevel = String.Empty;
  304. switch (iso) {
  305. case IsolationLevel.ReadUncommitted:
  306. isolevel = "READ UNCOMMITTED";
  307. break;
  308. case IsolationLevel.RepeatableRead:
  309. isolevel = "REPEATABLE READ";
  310. break;
  311. case IsolationLevel.Serializable:
  312. isolevel = "SERIALIZABLE";
  313. break;
  314. case IsolationLevel.ReadCommitted:
  315. isolevel = "READ COMMITTED";
  316. break;
  317. #if NET_2_0
  318. case IsolationLevel.Snapshot:
  319. isolevel = "SNAPSHOT";
  320. break;
  321. case IsolationLevel.Unspecified:
  322. iso = IsolationLevel.ReadCommitted;
  323. isolevel = "READ COMMITTED";
  324. break;
  325. case IsolationLevel.Chaos:
  326. throw new ArgumentOutOfRangeException ("IsolationLevel",
  327. string.Format (CultureInfo.CurrentCulture,
  328. "The IsolationLevel enumeration " +
  329. "value, {0}, is not supported by " +
  330. "the .Net Framework SqlClient " +
  331. "Data Provider.", (int) iso));
  332. #endif
  333. default:
  334. #if NET_2_0
  335. throw new ArgumentOutOfRangeException ("IsolationLevel",
  336. string.Format (CultureInfo.CurrentCulture,
  337. "The IsolationLevel enumeration value, {0}, is invalid.",
  338. (int) iso));
  339. #else
  340. throw new ArgumentException ("Invalid IsolationLevel parameter: must be ReadCommitted, ReadUncommitted, RepeatableRead, or Serializable.");
  341. #endif
  342. }
  343. tds.Execute (String.Format ("SET TRANSACTION ISOLATION LEVEL {0};BEGIN TRANSACTION {1}", isolevel, transactionName));
  344. transaction = new SqlTransaction (this, iso);
  345. return transaction;
  346. }
  347. public
  348. #if NET_2_0
  349. override
  350. #endif // NET_2_0
  351. void ChangeDatabase (string database)
  352. {
  353. if (!IsValidDatabaseName (database))
  354. throw new ArgumentException (String.Format ("The database name {0} is not valid.", database));
  355. if (state != ConnectionState.Open)
  356. throw new InvalidOperationException ("The connection is not open.");
  357. tds.Execute (String.Format ("use [{0}]", database));
  358. }
  359. private void ChangeState (ConnectionState currentState)
  360. {
  361. if (currentState == state)
  362. return;
  363. ConnectionState originalState = state;
  364. state = currentState;
  365. OnStateChange (CreateStateChangeEvent (originalState, currentState));
  366. }
  367. public
  368. #if NET_2_0
  369. override
  370. #endif // NET_2_0
  371. void Close ()
  372. {
  373. if (transaction != null && transaction.IsOpen)
  374. transaction.Rollback ();
  375. if (dataReader != null || xmlReader != null) {
  376. if(tds != null) tds.SkipToEnd ();
  377. dataReader = null;
  378. xmlReader = null;
  379. }
  380. if (tds != null && tds.IsConnected) {
  381. if (pooling && tds.Pooling) {
  382. if (pool != null) {
  383. pool.ReleaseConnection (tds);
  384. pool = null;
  385. }
  386. } else {
  387. tds.Disconnect ();
  388. }
  389. }
  390. if (tds != null) {
  391. tds.TdsErrorMessage -= new TdsInternalErrorMessageEventHandler (ErrorHandler);
  392. tds.TdsInfoMessage -= new TdsInternalInfoMessageEventHandler (MessageHandler);
  393. }
  394. ChangeState (ConnectionState.Closed);
  395. }
  396. public new SqlCommand CreateCommand ()
  397. {
  398. SqlCommand command = new SqlCommand ();
  399. command.Connection = this;
  400. return command;
  401. }
  402. private SqlInfoMessageEventArgs CreateSqlInfoMessageEvent (TdsInternalErrorCollection errors)
  403. {
  404. return new SqlInfoMessageEventArgs (errors);
  405. }
  406. private StateChangeEventArgs CreateStateChangeEvent (ConnectionState originalState, ConnectionState currentState)
  407. {
  408. return new StateChangeEventArgs (originalState, currentState);
  409. }
  410. protected override void Dispose (bool disposing)
  411. {
  412. try {
  413. if (disposing && !disposed) {
  414. if (State == ConnectionState.Open)
  415. Close ();
  416. ConnectionString = null;
  417. }
  418. } finally {
  419. disposed = true;
  420. base.Dispose (disposing);
  421. }
  422. }
  423. #if !MOBILE
  424. [MonoTODO ("Not sure what this means at present.")]
  425. public void EnlistDistributedTransaction (ITransaction transaction)
  426. {
  427. throw new NotImplementedException ();
  428. }
  429. #endif
  430. object ICloneable.Clone ()
  431. {
  432. return new SqlConnection (ConnectionString);
  433. }
  434. #if NET_2_0
  435. protected override DbTransaction BeginDbTransaction (IsolationLevel isolationLevel)
  436. {
  437. return BeginTransaction (isolationLevel);
  438. }
  439. protected override DbCommand CreateDbCommand ()
  440. {
  441. return CreateCommand ();
  442. }
  443. #else
  444. IDbTransaction IDbConnection.BeginTransaction ()
  445. {
  446. return BeginTransaction ();
  447. }
  448. IDbTransaction IDbConnection.BeginTransaction (IsolationLevel iso)
  449. {
  450. return BeginTransaction (iso);
  451. }
  452. IDbCommand IDbConnection.CreateCommand ()
  453. {
  454. return CreateCommand ();
  455. }
  456. #endif
  457. public
  458. #if NET_2_0
  459. override
  460. #endif // NET_2_0
  461. void Open ()
  462. {
  463. string serverName = string.Empty;
  464. if (state == ConnectionState.Open)
  465. throw new InvalidOperationException ("The Connection is already Open (State=Open)");
  466. if (connectionString == null || connectionString.Trim().Length == 0)
  467. throw new InvalidOperationException ("Connection string has not been initialized.");
  468. try {
  469. if (!pooling) {
  470. if(!ParseDataSource (dataSource, out port, out serverName))
  471. throw new SqlException(20, 0, "SQL Server does not exist or access denied.", 17, "ConnectionOpen (Connect()).", dataSource, parms.ApplicationName, 0);
  472. tds = new Tds80 (serverName, port, PacketSize, ConnectionTimeout, 0);
  473. tds.Pooling = false;
  474. }
  475. else {
  476. if(!ParseDataSource (dataSource, out port, out serverName))
  477. throw new SqlException(20, 0, "SQL Server does not exist or access denied.", 17, "ConnectionOpen (Connect()).", dataSource, parms.ApplicationName, 0);
  478. TdsConnectionInfo info = new TdsConnectionInfo (serverName, port, packetSize, ConnectionTimeout, minPoolSize, maxPoolSize, connectionLifeTime);
  479. pool = sqlConnectionPools.GetConnectionPool (connectionString, info);
  480. tds = pool.GetConnection ();
  481. }
  482. } catch (TdsTimeoutException e) {
  483. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  484. } catch (TdsInternalException e) {
  485. throw SqlException.FromTdsInternalException (e);
  486. }
  487. tds.TdsErrorMessage += new TdsInternalErrorMessageEventHandler (ErrorHandler);
  488. tds.TdsInfoMessage += new TdsInternalInfoMessageEventHandler (MessageHandler);
  489. if (!tds.IsConnected) {
  490. try {
  491. tds.Connect (parms);
  492. } catch {
  493. if (pooling)
  494. pool.ReleaseConnection (tds);
  495. throw;
  496. }
  497. }
  498. disposed = false; // reset this, so using () would call Close ().
  499. ChangeState (ConnectionState.Open);
  500. }
  501. private bool ParseDataSource (string theDataSource, out int thePort, out string theServerName)
  502. {
  503. theServerName = string.Empty;
  504. string theInstanceName = string.Empty;
  505. if (theDataSource == null)
  506. throw new ArgumentException("Format of initialization string does not conform to specifications");
  507. thePort = DEFAULT_PORT; // default TCP port for SQL Server
  508. bool success = true;
  509. int idx = 0;
  510. if ((idx = theDataSource.IndexOf (',')) > -1) {
  511. theServerName = theDataSource.Substring (0, idx);
  512. string p = theDataSource.Substring (idx + 1);
  513. thePort = Int32.Parse (p);
  514. } else if ((idx = theDataSource.IndexOf ('\\')) > -1) {
  515. theServerName = theDataSource.Substring (0, idx);
  516. theInstanceName = theDataSource.Substring (idx + 1);
  517. // do port discovery via UDP port 1434
  518. port = DiscoverTcpPortViaSqlMonitor (theServerName, theInstanceName);
  519. if (port == -1)
  520. success = false;
  521. } else
  522. theServerName = theDataSource;
  523. if (theServerName.Length == 0 || theServerName == "(local)" || theServerName == ".")
  524. theServerName = "localhost";
  525. if ((idx = theServerName.IndexOf ("tcp:")) > -1)
  526. theServerName = theServerName.Substring (idx + 4);
  527. return success;
  528. }
  529. private bool ConvertIntegratedSecurity (string value)
  530. {
  531. if (value.ToUpper() == "SSPI")
  532. return true;
  533. return ConvertToBoolean ("integrated security", value, false);
  534. }
  535. private bool ConvertToBoolean (string key, string value, bool defaultValue)
  536. {
  537. if (value.Length == 0)
  538. return defaultValue;
  539. string upperValue = value.ToUpper ();
  540. if (upperValue == "TRUE" || upperValue == "YES")
  541. return true;
  542. else if (upperValue == "FALSE" || upperValue == "NO")
  543. return false;
  544. throw new ArgumentException (string.Format (CultureInfo.InvariantCulture,
  545. "Invalid value \"{0}\" for key '{1}'.", value, key));
  546. }
  547. private int ConvertToInt32 (string key, string value, int defaultValue)
  548. {
  549. if (value.Length == 0)
  550. return defaultValue;
  551. try {
  552. return int.Parse (value);
  553. } catch (Exception ex) {
  554. throw new ArgumentException (string.Format (CultureInfo.InvariantCulture,
  555. "Invalid value \"{0}\" for key '{1}'.", value, key), ex);
  556. }
  557. }
  558. private int DiscoverTcpPortViaSqlMonitor (string ServerName, string InstanceName)
  559. {
  560. SqlMonitorSocket msock;
  561. msock = new SqlMonitorSocket (ServerName, InstanceName);
  562. int SqlServerPort = msock.DiscoverTcpPort (ConnectionTimeout);
  563. msock = null;
  564. return SqlServerPort;
  565. }
  566. void SetConnectionString (string connectionString)
  567. {
  568. SetDefaultConnectionParameters ();
  569. if ((connectionString == null) || (connectionString.Trim().Length == 0)) {
  570. this.connectionString = connectionString;
  571. return;
  572. }
  573. connectionString += ";";
  574. bool inQuote = false;
  575. bool inDQuote = false;
  576. bool inName = true;
  577. string name = String.Empty;
  578. string value = String.Empty;
  579. StringBuilder sb = new StringBuilder ();
  580. for (int i = 0; i < connectionString.Length; i += 1) {
  581. char c = connectionString [i];
  582. char peek;
  583. if (i == connectionString.Length - 1)
  584. peek = '\0';
  585. else
  586. peek = connectionString [i + 1];
  587. switch (c) {
  588. case '\'':
  589. if (inDQuote)
  590. sb.Append (c);
  591. else if (peek.Equals (c)) {
  592. sb.Append (c);
  593. i += 1;
  594. }
  595. else
  596. inQuote = !inQuote;
  597. break;
  598. case '"':
  599. if (inQuote)
  600. sb.Append (c);
  601. else if (peek.Equals (c)) {
  602. sb.Append (c);
  603. i += 1;
  604. }
  605. else
  606. inDQuote = !inDQuote;
  607. break;
  608. case ';':
  609. if (inDQuote || inQuote)
  610. sb.Append (c);
  611. else {
  612. if (name != String.Empty && name != null) {
  613. value = sb.ToString ();
  614. SetProperties (name.ToLower ().Trim() , value);
  615. }
  616. else if (sb.Length != 0)
  617. throw new ArgumentException ("Format of initialization string does not conform to specifications");
  618. inName = true;
  619. name = String.Empty;
  620. value = String.Empty;
  621. sb = new StringBuilder ();
  622. }
  623. break;
  624. case '=':
  625. if (inDQuote || inQuote || !inName)
  626. sb.Append (c);
  627. else if (peek.Equals (c)) {
  628. sb.Append (c);
  629. i += 1;
  630. }
  631. else {
  632. name = sb.ToString ();
  633. sb = new StringBuilder ();
  634. inName = false;
  635. }
  636. break;
  637. case ' ':
  638. if (inQuote || inDQuote)
  639. sb.Append (c);
  640. else if (sb.Length > 0 && !peek.Equals (';'))
  641. sb.Append (c);
  642. break;
  643. default:
  644. sb.Append (c);
  645. break;
  646. }
  647. }
  648. if (minPoolSize > maxPoolSize)
  649. throw new ArgumentException ("Invalid value for "
  650. + "'min pool size' or 'max pool size'; "
  651. + "'min pool size' must not be greater "
  652. + "than 'max pool size'.");
  653. connectionString = connectionString.Substring (0 , connectionString.Length-1);
  654. this.connectionString = connectionString;
  655. }
  656. void SetDefaultConnectionParameters ()
  657. {
  658. if (parms == null)
  659. parms = new TdsConnectionParameters ();
  660. else
  661. parms.Reset ();
  662. dataSource = string.Empty;
  663. connectionTimeout = DEFAULT_CONNECTIONTIMEOUT;
  664. connectionLifeTime = DEFAULT_CONNECTIONLIFETIME;
  665. connectionReset = true;
  666. pooling = true;
  667. maxPoolSize = DEFAULT_MAXPOOLSIZE;
  668. minPoolSize = DEFAULT_MINPOOLSIZE;
  669. packetSize = DEFAULT_PACKETSIZE;
  670. port = DEFAULT_PORT;
  671. #if NET_2_0
  672. async = false;
  673. #endif
  674. }
  675. private void SetProperties (string name , string value)
  676. {
  677. switch (name) {
  678. case "app" :
  679. case "application name" :
  680. parms.ApplicationName = value;
  681. break;
  682. case "attachdbfilename" :
  683. case "extended properties" :
  684. case "initial file name" :
  685. parms.AttachDBFileName = value;
  686. break;
  687. case "timeout" :
  688. case "connect timeout" :
  689. case "connection timeout" :
  690. int tmpTimeout = ConvertToInt32 ("connect timeout", value,
  691. DEFAULT_CONNECTIONTIMEOUT);
  692. if (tmpTimeout < 0)
  693. throw new ArgumentException ("Invalid 'connect timeout'. Must be an integer >=0 ");
  694. else
  695. connectionTimeout = tmpTimeout;
  696. break;
  697. case "connection lifetime" :
  698. connectionLifeTime = ConvertToInt32 ("connection lifetime", value, DEFAULT_CONNECTIONLIFETIME);
  699. break;
  700. case "connection reset" :
  701. connectionReset = ConvertToBoolean ("connection reset", value, true);
  702. break;
  703. case "language" :
  704. case "current language" :
  705. parms.Language = value;
  706. break;
  707. case "data source" :
  708. case "server" :
  709. case "address" :
  710. case "addr" :
  711. case "network address" :
  712. dataSource = value;
  713. break;
  714. case "encrypt":
  715. if (ConvertToBoolean (name, value, false))
  716. throw new NotImplementedException("SSL encryption for"
  717. + " data sent between client and server is not"
  718. + " implemented.");
  719. break;
  720. case "enlist" :
  721. if (!ConvertToBoolean (name, value, true))
  722. throw new NotImplementedException("Disabling the automatic"
  723. + " enlistment of connections in the thread's current"
  724. + " transaction context is not implemented.");
  725. break;
  726. case "initial catalog" :
  727. case "database" :
  728. parms.Database = value;
  729. break;
  730. case "integrated security" :
  731. case "trusted_connection" :
  732. parms.DomainLogin = ConvertIntegratedSecurity(value);
  733. break;
  734. case "max pool size" :
  735. int tmpMaxPoolSize = ConvertToInt32 (name, value, DEFAULT_MAXPOOLSIZE);
  736. if (tmpMaxPoolSize < MIN_MAXPOOLSIZE)
  737. throw new ArgumentException (string.Format (CultureInfo.InvariantCulture,
  738. "Invalid '{0}'. The value must be greater than {1}.",
  739. name, MIN_MAXPOOLSIZE));
  740. else
  741. maxPoolSize = tmpMaxPoolSize;
  742. break;
  743. case "min pool size" :
  744. int tmpMinPoolSize = ConvertToInt32 (name, value, DEFAULT_MINPOOLSIZE);
  745. if (tmpMinPoolSize < 0)
  746. throw new ArgumentException ("Invalid 'min pool size'. Must be a integer >= 0");
  747. else
  748. minPoolSize = tmpMinPoolSize;
  749. break;
  750. #if NET_2_0
  751. case "multipleactiveresultsets":
  752. // FIXME: not implemented
  753. ConvertToBoolean (name, value, false);
  754. break;
  755. case "asynchronous processing" :
  756. case "async" :
  757. async = ConvertToBoolean (name, value, false);
  758. break;
  759. #endif
  760. case "net" :
  761. case "network" :
  762. case "network library" :
  763. if (!value.ToUpper ().Equals ("DBMSSOCN"))
  764. throw new ArgumentException ("Unsupported network library.");
  765. break;
  766. case "packet size" :
  767. int tmpPacketSize = ConvertToInt32 (name, value, DEFAULT_PACKETSIZE);
  768. if (tmpPacketSize < MIN_PACKETSIZE || tmpPacketSize > MAX_PACKETSIZE)
  769. throw new ArgumentException (string.Format (CultureInfo.InvariantCulture,
  770. "Invalid 'Packet Size'. The value must be between {0} and {1}.",
  771. MIN_PACKETSIZE, MAX_PACKETSIZE));
  772. else
  773. packetSize = tmpPacketSize;
  774. break;
  775. case "password" :
  776. case "pwd" :
  777. parms.Password = value;
  778. break;
  779. case "persistsecurityinfo" :
  780. case "persist security info" :
  781. // FIXME : not implemented
  782. // throw new NotImplementedException ();
  783. break;
  784. case "pooling" :
  785. pooling = ConvertToBoolean (name, value, true);
  786. break;
  787. case "uid" :
  788. case "user" :
  789. case "user id" :
  790. parms.User = value;
  791. break;
  792. case "wsid" :
  793. case "workstation id" :
  794. parms.Hostname = value;
  795. break;
  796. #if NET_2_0
  797. case "user instance":
  798. userInstance = ConvertToBoolean (name, value, false);
  799. break;
  800. #endif
  801. default :
  802. throw new ArgumentException("Keyword not supported : '" + name + "'.");
  803. }
  804. }
  805. static bool IsValidDatabaseName (string database)
  806. {
  807. if ( database == null || database.Trim().Length == 0 || database.Length > 128)
  808. return false ;
  809. if (database[0] == '"' && database[database.Length] == '"')
  810. database = database.Substring (1, database.Length - 2);
  811. else if (Char.IsDigit (database[0]))
  812. return false;
  813. if (database[0] == '_')
  814. return false;
  815. foreach (char c in database.Substring (1, database.Length - 1))
  816. if (!Char.IsLetterOrDigit (c) && c != '_' && c != '-')
  817. return false;
  818. return true;
  819. }
  820. private void OnSqlInfoMessage (SqlInfoMessageEventArgs value)
  821. {
  822. if (InfoMessage != null)
  823. InfoMessage (this, value);
  824. }
  825. #if !NET_2_0
  826. private new void OnStateChange (StateChangeEventArgs value)
  827. {
  828. if (StateChange != null)
  829. StateChange (this, value);
  830. }
  831. #endif
  832. private sealed class SqlMonitorSocket : UdpClient
  833. {
  834. // UDP port that the SQL Monitor listens
  835. private static readonly int SqlMonitorUdpPort = 1434;
  836. //private static readonly string SqlServerNotExist = "SQL Server does not exist or access denied";
  837. private string server;
  838. private string instance;
  839. internal SqlMonitorSocket (string ServerName, string InstanceName)
  840. : base (ServerName, SqlMonitorUdpPort)
  841. {
  842. server = ServerName;
  843. instance = InstanceName;
  844. }
  845. internal int DiscoverTcpPort (int timeoutSeconds)
  846. {
  847. int SqlServerTcpPort;
  848. Client.Blocking = false;
  849. // send command to UDP 1434 (SQL Monitor) to get
  850. // the TCP port to connect to the MS SQL server
  851. ASCIIEncoding enc = new ASCIIEncoding ();
  852. Byte[] rawrq = new Byte [instance.Length + 1];
  853. rawrq[0] = 4;
  854. enc.GetBytes (instance, 0, instance.Length, rawrq, 1);
  855. Send (rawrq, rawrq.Length);
  856. if (!Active)
  857. return -1; // Error
  858. bool result;
  859. long timeout = timeoutSeconds * 1000000;
  860. result = Client.Poll ((int)timeout, SelectMode.SelectRead);
  861. if (result == false)
  862. return -1; // Error
  863. if (Client.Available <= 0)
  864. return -1; // Error
  865. #if NET_2_0
  866. IPEndPoint endpoint = new IPEndPoint (Dns.GetHostEntry ("localhost").AddressList [0], 0);
  867. #else
  868. IPEndPoint endpoint = new IPEndPoint (Dns.GetHostByName ("localhost").AddressList [0], 0);
  869. #endif
  870. Byte [] rawrs;
  871. rawrs = Receive (ref endpoint);
  872. string rs = Encoding.ASCII.GetString (rawrs);
  873. string[] rawtokens = rs.Split (';');
  874. Hashtable data = new Hashtable ();
  875. for (int i = 0; i < rawtokens.Length / 2 && i < 256; i++) {
  876. data [rawtokens [i * 2]] = rawtokens [ i * 2 + 1];
  877. }
  878. if (!data.ContainsKey ("tcp")) {
  879. string msg = "Mono does not support names pipes or shared memory "
  880. + "for connecting to SQL Server. Please enable the TCP/IP "
  881. + "protocol.";
  882. throw new NotImplementedException (msg);
  883. }
  884. SqlServerTcpPort = int.Parse ((string) data ["tcp"]);
  885. Close ();
  886. return SqlServerTcpPort;
  887. }
  888. }
  889. #if NET_2_0
  890. struct ColumnInfo
  891. {
  892. public string name;
  893. public Type type;
  894. public ColumnInfo (string name, Type type)
  895. {
  896. this.name = name; this.type = type;
  897. }
  898. }
  899. static class ReservedWords
  900. {
  901. static readonly string [] reservedWords =
  902. {
  903. "ADD", "EXCEPT", "PERCENT", "ALL", "EXEC", "PLAN", "ALTER",
  904. "EXECUTE", "PRECISION", "AND", "EXISTS", "PRIMARY", "ANY",
  905. "EXIT", "PRINT", "AS", "FETCH", "PROC", "ASC", "FILE",
  906. "PROCEDURE", "AUTHORIZATION", "FILLFACTOR", "PUBLIC",
  907. "BACKUP", "FOR", "RAISERROR", "BEGIN", "FOREIGN", "READ",
  908. "BETWEEN", "FREETEXT", "READTEXT", "BREAK", "FREETEXTTABLE",
  909. "RECONFIGURE", "BROWSE", "FROM", "REFERENCES", "BULK",
  910. "FULL", "REPLICATION", "BY", "FUNCTION", "RESTORE",
  911. "CASCADE", "GOTO", "RESTRICT", "CASE", "GRANT", "RETURN",
  912. "CHECK", "GROUP", "REVOKE", "CHECKPOINT", "HAVING", "RIGHT",
  913. "CLOSE", "HOLDLOCK", "ROLLBACK", "CLUSTERED", "IDENTITY",
  914. "ROWCOUNT", "COALESCE", "IDENTITY_INSERT", "ROWGUIDCOL",
  915. "COLLATE", "IDENTITYCOL", "RULE", "COLUMN", "IF", "SAVE",
  916. "COMMIT", "IN", "SCHEMA", "COMPUTE", "INDEX", "SELECT",
  917. "CONSTRAINT", "INNER", "SESSION_USER", "CONTAINS", "INSERT",
  918. "SET", "CONTAINSTABLE", "INTERSECT", "SETUSER", "CONTINUE",
  919. "INTO", "SHUTDOWN", "CONVERT", "IS", "SOME", "CREATE",
  920. "JOIN", "STATISTICS", "CROSS", "KEY", "SYSTEM_USER",
  921. "CURRENT", "KILL", "TABLE", "CURRENT_DATE", "LEFT",
  922. "TEXTSIZE", "CURRENT_TIME", "LIKE", "THEN",
  923. "CURRENT_TIMESTAMP", "LINENO", "TO", "CURRENT_USER", "LOAD",
  924. "TOP", "CURSOR", "NATIONAL", "TRAN", "DATABASE", "NOCHECK",
  925. "TRANSACTION", "DBCC", "NONCLUSTERED", "TRIGGER",
  926. "DEALLOCATE", "NOT", "TRUNCATE", "DECLARE", "NULL",
  927. "TSEQUAL", "DEFAULT", "NULLIF", "UNION", "DELETE", "OF",
  928. "UNIQUE", "DENY", "OFF", "UPDATE", "DESC", "OFFSETS",
  929. "UPDATETEXT", "DISK", "ON", "USE", "DISTINCT", "OPEN",
  930. "USER", "DISTRIBUTED", "OPENDATASOURCE", "VALUES", "DOUBLE",
  931. "OPENQUERY", "VARYING", "DROP", "OPENROWSET", "VIEW",
  932. "DUMMY", "OPENXML", "WAITFOR", "DUMP", "OPTION", "WHEN",
  933. "ELSE", "OR", "WHERE", "END", "ORDER", "WHILE", "ERRLVL",
  934. "OUTER", "WITH", "ESCAPE", "OVER", "WRITETEXT", "ABSOLUTE",
  935. "FOUND", "PRESERVE", "ACTION", "FREE", "PRIOR", "ADMIN",
  936. "GENERAL", "PRIVILEGES", "AFTER", "GET", "READS",
  937. "AGGREGATE", "GLOBAL", "REAL", "ALIAS", "GO", "RECURSIVE",
  938. "ALLOCATE", "GROUPING", "REF", "ARE", "HOST", "REFERENCING",
  939. "ARRAY", "HOUR", "RELATIVE", "ASSERTION", "IGNORE", "RESULT",
  940. "AT", "IMMEDIATE", "RETURNS", "BEFORE", "INDICATOR", "ROLE",
  941. "BINARY", "INITIALIZE", "ROLLUP", "BIT", "INITIALLY",
  942. "ROUTINE", "BLOB", "INOUT", "ROW", "BOOLEAN", "INPUT",
  943. "ROWS", "BOTH", "INT", "SAVEPOINT", "BREADTH", "INTEGER",
  944. "SCROLL", "CALL", "INTERVAL", "SCOPE", "CASCADED",
  945. "ISOLATION", "SEARCH", "CAST", "ITERATE", "SECOND",
  946. "CATALOG", "LANGUAGE", "SECTION", "CHAR", "LARGE",
  947. "SEQUENCE", "CHARACTER", "LAST", "SESSION", "CLASS",
  948. "LATERAL", "SETS", "CLOB", "LEADING", "SIZE", "COLLATION",
  949. "LESS", "SMALLINT", "COMPLETION", "LEVEL", "SPACE",
  950. "CONNECT", "LIMIT", "SPECIFIC", "CONNECTION", "LOCAL",
  951. "SPECIFICTYPE", "CONSTRAINTS", "LOCALTIME", "SQL",
  952. "CONSTRUCTOR", "LOCALTIMESTAMP", "SQLEXCEPTION",
  953. "CORRESPONDING", "LOCATOR", "SQLSTATE", "CUBE", "MAP",
  954. "SQLWARNING", "CURRENT_PATH", "MATCH", "START",
  955. "CURRENT_ROLE", "MINUTE", "STATE", "CYCLE", "MODIFIES",
  956. "STATEMENT", "DATA", "MODIFY", "STATIC", "DATE", "MODULE",
  957. "STRUCTURE", "DAY", "MONTH", "TEMPORARY", "DEC", "NAMES",
  958. "TERMINATE", "DECIMAL", "NATURAL", "THAN", "DEFERRABLE",
  959. "NCHAR", "TIME", "DEFERRED", "NCLOB", "TIMESTAMP", "DEPTH",
  960. "NEW", "TIMEZONE_HOUR", "DEREF", "NEXT", "TIMEZONE_MINUTE",
  961. "DESCRIBE", "NO", "TRAILING", "DESCRIPTOR", "NONE",
  962. "TRANSLATION", "DESTROY", "NUMERIC", "TREAT", "DESTRUCTOR",
  963. "OBJECT", "TRUE", "DETERMINISTIC", "OLD", "UNDER",
  964. "DICTIONARY", "ONLY", "UNKNOWN", "DIAGNOSTICS", "OPERATION",
  965. "UNNEST", "DISCONNECT", "ORDINALITY", "USAGE", "DOMAIN",
  966. "OUT", "USING", "DYNAMIC", "OUTPUT", "VALUE", "EACH",
  967. "PAD", "VARCHAR", "END-EXEC", "PARAMETER", "VARIABLE",
  968. "EQUALS", "PARAMETERS", "WHENEVER", "EVERY", "PARTIAL",
  969. "WITHOUT", "EXCEPTION", "PATH", "WORK", "EXTERNAL",
  970. "POSTFIX", "WRITE", "FALSE", "PREFIX", "YEAR", "FIRST",
  971. "PREORDER", "ZONE", "FLOAT", "PREPARE", "ADA", "AVG",
  972. "BIT_LENGTH", "CHAR_LENGTH", "CHARACTER_LENGTH", "COUNT",
  973. "EXTRACT", "FORTRAN", "INCLUDE", "INSENSITIVE", "LOWER",
  974. "MAX", "MIN", "OCTET_LENGTH", "OVERLAPS", "PASCAL",
  975. "POSITION", "SQLCA", "SQLCODE", "SQLERROR", "SUBSTRING",
  976. "SUM", "TRANSLATE", "TRIM", "UPPER"
  977. };
  978. static DataTable instance;
  979. static public DataTable Instance {
  980. get {
  981. if (instance == null) {
  982. DataRow row = null;
  983. var newInstance = new DataTable ("ReservedWords");
  984. newInstance.Columns.Add ("ReservedWord", typeof(string));
  985. foreach (string reservedWord in reservedWords)
  986. {
  987. row = newInstance.NewRow();
  988. row["ReservedWord"] = reservedWord;
  989. newInstance.Rows.Add(row);
  990. }
  991. instance = newInstance;
  992. }
  993. return instance;
  994. }
  995. }
  996. }
  997. static class MetaDataCollections
  998. {
  999. static readonly ColumnInfo [] columns = {
  1000. new ColumnInfo ("CollectionName", typeof (string)),
  1001. new ColumnInfo ("NumberOfRestrictions", typeof (int)),
  1002. new ColumnInfo ("NumberOfIdentifierParts", typeof (int))
  1003. };
  1004. static readonly object [][] rows = {
  1005. new object [] {"MetaDataCollections", 0, 0},
  1006. new object [] {"DataSourceInformation", 0, 0},
  1007. new object [] {"DataTypes", 0, 0},
  1008. new object [] {"Restrictions", 0, 0},
  1009. new object [] {"ReservedWords", 0, 0},
  1010. new object [] {"Users", 1, 1},
  1011. new object [] {"Databases", 1, 1},
  1012. new object [] {"Tables", 4, 3},
  1013. new object [] {"Columns", 4, 4},
  1014. new object [] {"StructuredTypeMembers", 4, 4},
  1015. new object [] {"Views", 3, 3},
  1016. new object [] {"ViewColumns", 4, 4},
  1017. new object [] {"ProcedureParameters", 4, 1},
  1018. new object [] {"Procedures", 4, 3},
  1019. new object [] {"ForeignKeys", 4, 3},
  1020. new object [] {"IndexColumns", 5, 4},
  1021. new object [] {"Indexes", 4, 3},
  1022. new object [] {"UserDefinedTypes", 2, 1}
  1023. };
  1024. static DataTable instance;
  1025. static public DataTable Instance {
  1026. get {
  1027. if (instance == null) {
  1028. var newInstance = new DataTable ("MetaDataCollections");
  1029. foreach (ColumnInfo c in columns)
  1030. newInstance.Columns.Add (c.name, c.type);
  1031. foreach (object [] row in rows)
  1032. newInstance.LoadDataRow (row, true);
  1033. instance = newInstance;
  1034. }
  1035. return instance;
  1036. }
  1037. }
  1038. }
  1039. static class DataSourceInformation
  1040. {
  1041. static readonly ColumnInfo [] columns = {
  1042. new ColumnInfo ("CompositeIdentifierSeparatorPattern", typeof (string)),
  1043. new ColumnInfo ("DataSourceProductName", typeof(string)),
  1044. new ColumnInfo ("DataSourceProductVersion", typeof(string)),
  1045. new ColumnInfo ("DataSourceProductVersionNormalized", typeof(string)),
  1046. new ColumnInfo ("GroupByBehavior", typeof(GroupByBehavior)),
  1047. new ColumnInfo ("IdentifierPattern", typeof(string)),
  1048. new ColumnInfo ("IdentifierCase", typeof(IdentifierCase)),
  1049. new ColumnInfo ("OrderByColumnsInSelect", typeof(bool)),
  1050. new ColumnInfo ("ParameterMarkerFormat", typeof(string)),
  1051. new ColumnInfo ("ParameterMarkerPattern", typeof(string)),
  1052. new ColumnInfo ("ParameterNameMaxLength", typeof(int)),
  1053. new ColumnInfo ("ParameterNamePattern", typeof(string)),
  1054. new ColumnInfo ("QuotedIdentifierPattern", typeof(string)),
  1055. new ColumnInfo ("QuotedIdentifierCase", typeof(IdentifierCase)),
  1056. new ColumnInfo ("StatementSeparatorPattern", typeof(string)),
  1057. new ColumnInfo ("StringLiteralPattern", typeof(string)),
  1058. new ColumnInfo ("SupportedJoinOperators", typeof(SupportedJoinOperators))
  1059. };
  1060. static public DataTable GetInstance (SqlConnection conn)
  1061. {
  1062. DataTable table = new DataTable ("DataSourceInformation");
  1063. foreach (ColumnInfo c in columns)
  1064. table.Columns.Add (c.name, c.type);
  1065. DataRow row = table.NewRow ();
  1066. row [0] = "\\.";
  1067. row [1] = "Microsoft SQL Server";
  1068. row [2] = conn.ServerVersion;;
  1069. row [3] = conn.ServerVersion;;
  1070. row [4] = GroupByBehavior.Unrelated;
  1071. row [5] = @"(^\[\p{Lo}\p{Lu}\p{Ll}_@#][\p{Lo}\p{Lu}\p{Ll}\p{Nd}@$#_]*$)|(^\[[^\]\0]|\]\]+\]$)|(^\""[^\""\0]|\""\""+\""$)";
  1072. row [6] = IdentifierCase.Insensitive; // FIXME: obtain this from SQL Server
  1073. row [7] = false;
  1074. row [8] = "{0}";
  1075. row [9] = @"@[\p{Lo}\p{Lu}\p{Ll}\p{Lm}_@#][\p{Lo}\p{Lu}\p{Ll}\p{Lm}\p{Nd}\uff3f_@#\$]*(?=\s+|$)";
  1076. row [10] = 128;
  1077. row [11] = @"^[\p{Lo}\p{Lu}\p{Ll}\p{Lm}_@#][\p{Lo}\p{Lu}\p{Ll}\p{Lm}\p{Nd}\uff3f_@#\$]*(?=\s+|$)";
  1078. row [12] = @"(([^\[]|\]\])*)";
  1079. row [13] = IdentifierCase.Insensitive; // FIXME: obtain this from SQL Server
  1080. row [14] =";";
  1081. row [15] = "'(([^']|'')*)'";
  1082. row [16] = (SupportedJoinOperators.FullOuter | SupportedJoinOperators.Inner |
  1083. SupportedJoinOperators.LeftOuter | SupportedJoinOperators.RightOuter);
  1084. table.Rows.Add (row);
  1085. return table;
  1086. }
  1087. }
  1088. static class DataTypes
  1089. {
  1090. static readonly ColumnInfo [] columns = {
  1091. new ColumnInfo ("TypeName", typeof(string)),
  1092. new ColumnInfo ("ProviderDbType", typeof(int)),
  1093. new ColumnInfo ("ColumnSize", typeof(long)),
  1094. new ColumnInfo ("CreateFormat", typeof(string)),
  1095. new ColumnInfo ("CreateParameters", typeof(string)),
  1096. new ColumnInfo ("DataType", typeof(string)),
  1097. new ColumnInfo ("IsAutoIncrementable", typeof(bool)),
  1098. new ColumnInfo ("IsBestMatch", typeof(bool)),
  1099. new ColumnInfo ("IsCaseSensitive", typeof(bool)),
  1100. new ColumnInfo ("IsFixedLength", typeof(bool)),
  1101. new ColumnInfo ("IsFixedPrecisionScale", typeof(bool)),
  1102. new ColumnInfo ("IsLong", typeof(bool)),
  1103. new ColumnInfo ("IsNullable", typeof(bool)),
  1104. new ColumnInfo ("IsSearchable", typeof(bool)),
  1105. new ColumnInfo ("IsSearchableWithLike", typeof(bool)),
  1106. new ColumnInfo ("IsUnsigned", typeof(bool)),
  1107. new ColumnInfo ("MaximumScale", typeof(short)),
  1108. new ColumnInfo ("MinimumScale", typeof(short)),
  1109. new ColumnInfo ("IsConcurrencyType", typeof(bool)),
  1110. new ColumnInfo ("IsLiteralSupported", typeof(bool)),
  1111. new ColumnInfo ("LiteralPrefix", typeof(string)),
  1112. new ColumnInfo ("LiteralSuffix", typeof(string))
  1113. };
  1114. static readonly object [][] rows = {
  1115. new object [] {"smallint", 16, 5, "smallint", null, "System.Int16", true, true,
  1116. false, true, true, false, true, true, false, false, null,
  1117. null, false, null, null, null},
  1118. new object [] {"int", 8, 10, "int", null, "System.Int32",
  1119. true, true, false, true, true, false, true, true, false,
  1120. false, null, null, false, null, null, null},
  1121. new object [] {"real", 13, 7, "real", null,
  1122. "System.Single", false, true, false, true, false, false,
  1123. true, true, false, false, null, null, false, null, null, null},
  1124. new object [] {"float", 6, 53, "float({0})",
  1125. "number of bits used to store the mantissa", "System.Double",
  1126. false, true, false, true, false, false, true, true,
  1127. false, false, null, null, false, null, null, null},
  1128. new object [] {"money", 9, 19, "money", null,
  1129. "System.Decimal", false, false, false, true, true,
  1130. false, true, true, false, false, null, null, false,
  1131. null, null, null},
  1132. new object [] {"smallmoney", 17, 10, "smallmoney", null,
  1133. "System.Decimal", false, false, false, true, true, false,
  1134. true, true, false, false, null, null, false, null, null, null},
  1135. new object [] {"bit", 2, 1, "bit", null, "System.Boolean",
  1136. false, false, false, true, false, false, true, true,
  1137. false, null, null, null, false, null, null, null},
  1138. new object [] {"tinyint", 20, 3, "tinyint", null,
  1139. "System.SByte", true, true, false, true, true, false,
  1140. true, true, false, true, null, null, false, null, null, null},
  1141. new object [] {"bigint", 0, 19, "bigint", null,
  1142. "System.Int64", true, true, false, true, true, false,
  1143. true, true, false, false, null, null, false, null, null, null},
  1144. new object [] {"timestamp", 19, 8, "timestamp", null,
  1145. "System.Byte[]", false, false, false, true, false, false,
  1146. false, true, false, null, null, null, true, null, "0x", null},
  1147. new object [] {"binary", 1, 8000, "binary({0})", "length",
  1148. "System.Byte[]", false, true, false, true, false, false,
  1149. true, true, false, null, null, null, false, null, "0x", null},
  1150. new object [] {"image", 7, 2147483647, "image", null,
  1151. "System.Byte[]", false, true, false, false, false, true,
  1152. true, false, false, null, null, null, false, null, "0x", null},
  1153. new object [] {"text", 18, 2147483647, "text", null,
  1154. "System.String", false, true, false, false, false, true,
  1155. true, false, true, null, null, null, false, null, "'", "'"},
  1156. new object [] {"ntext", 11, 1073741823, "ntext", null,
  1157. "System.String", false, true, false, false, false, true,
  1158. true, false, true, null, null, null, false, null, "N'", "'"},
  1159. new object [] {"decimal", 5, 38, "decimal({0}, {1})",
  1160. "precision,scale", "System.Decimal", true, true, false,
  1161. true, false, false, true, true, false, false, 38, 0,
  1162. false, null, null, null},
  1163. new object [] {"numeric", 5, 38, "numeric({0}, {1})",
  1164. "precision,scale", "System.Decimal", true, true, false,
  1165. true, false, false, true, true, false, false, 38, 0,
  1166. false, null, null, null},
  1167. new object [] {"datetime", 4, 23, "datetime", null,
  1168. "System.DateTime", false, true, false, true, false, false,
  1169. true, true, true, null, null, null, false, null, "{ts '", "'}"},
  1170. new object [] {"smalldatetime", 15, 16, "smalldatetime", null,
  1171. "System.DateTime", false, true, false, true, false, false,
  1172. true, true, true, null, null, null, false, null, "{ts '", "'}"},
  1173. new object [] {"sql_variant", 23, null, "sql_variant",
  1174. null, "System.Object", false, true, false, false, false,
  1175. false, true, true, false, null, null, null, false, false,
  1176. null, null},
  1177. new object [] {"xml", 25, 2147483647, "xml", null,
  1178. "System.String", false, false, false, false, false, true,
  1179. true, false, false, null, null, null, false, false, null, null},
  1180. new object [] {"varchar", 22, 2147483647, "varchar({0})",
  1181. "max length", "System.String", false, true, false, false,
  1182. false, false, true, true, true, null, null, null, false,
  1183. null, "'", "'"},
  1184. new object [] {"char", 3, 2147483647, "char({0})", "length",
  1185. "System.String", false, true, false, true, false, false,
  1186. true, true, true, null, null, null, false, null, "'", "'"},
  1187. new object [] {"nchar", 10, 1073741823, "nchar({0})", "length",
  1188. "System.String", false, true, false, true, false, false,
  1189. true, true, true, null, null, null, false, null, "N'", "'"},
  1190. new object [] {"nvarchar", 12, 1073741823, "nvarchar({0})", "max length",
  1191. "System.String", false, true, false, false, false, false, true, true,
  1192. true, null, null, null, false, null, "N'", "'"},
  1193. new object [] {"varbinary", 21, 1073741823, "varbinary({0})",
  1194. "max length", "System.Byte[]", false, true, false, false,
  1195. false, false, true, true, false, null, null, null, false,
  1196. null, "0x", null},
  1197. new object [] {"uniqueidentifier", 14, 16, "uniqueidentifier", null,
  1198. "System.Guid", false, true, false, true, false, false, true,
  1199. true, false, null, null, null, false, null, "'", "'"},
  1200. new object [] {"date", 31, 3L, "date", DBNull.Value,
  1201. "System.DateTime", false, false, false, true, true, false,
  1202. true, true, true, DBNull.Value, DBNull.Value, DBNull.Value,
  1203. false, DBNull.Value, "{ts '", "'}"},
  1204. new object [] {"time", 32, 5L, "time({0})", "scale",
  1205. "System.TimeSpan", false, false, false, false, false, false,
  1206. true, true, true, DBNull.Value, (short) 7, (short) 0,
  1207. false, DBNull.Value, "{ts '", "'}"},
  1208. new object [] {"datetime2", 33, 8L, "datetime2({0})", "scale",
  1209. "System.DateTime", false, true, false, false, false, false,
  1210. true, true, true, DBNull.Value, (short) 7, (short) 0,
  1211. false, DBNull.Value, "{ts '", "'}"},
  1212. new object [] {"datetimeoffset", 34, 10L, "datetimeoffset({0})",
  1213. "scale", "System.DateTimeOffset", false, true, false, false,
  1214. false, false, true, true, true, DBNull.Value, (short) 7, (short) 0,
  1215. false, DBNull.Value, "{ts '", "'}"}
  1216. };
  1217. static DataTable instance;
  1218. static public DataTable Instance {
  1219. get {
  1220. if (instance == null) {
  1221. instance = new DataTable ("DataTypes");
  1222. foreach (ColumnInfo c in columns)
  1223. instance.Columns.Add (c.name, c.type);
  1224. foreach (object [] row in rows)
  1225. instance.LoadDataRow (row, true);
  1226. }
  1227. return instance;
  1228. }
  1229. }
  1230. }
  1231. static class Restrictions
  1232. {
  1233. static readonly ColumnInfo [] columns = {
  1234. new ColumnInfo ("CollectionName", typeof (string)),
  1235. new ColumnInfo ("RestrictionName", typeof(string)),
  1236. new ColumnInfo ("ParameterName", typeof(string)),
  1237. new ColumnInfo ("RestrictionDefault", typeof(string)),
  1238. new ColumnInfo ("RestrictionNumber", typeof(int))
  1239. };
  1240. static readonly object [][] rows = {
  1241. new object [] {"Users", "User_Name", "@Name", "name", 1},
  1242. new object [] {"Databases", "Name", "@Name", "Name", 1},
  1243. new object [] {"Tables", "Catalog", "@Catalog", "TABLE_CATALOG", 1},
  1244. new object [] {"Tables", "Owner", "@Owner", "TABLE_SCHEMA", 2},
  1245. new object [] {"Tables", "Table", "@Name", "TABLE_NAME", 3},
  1246. new object [] {"Tables", "TableType", "@TableType", "TABLE_TYPE", 4},
  1247. new object [] {"Columns", "Catalog", "@Catalog", "TABLE_CATALOG", 1},
  1248. new object [] {"Columns", "Owner", "@Owner", "TABLE_SCHEMA", 2},
  1249. new object [] {"Columns", "Table", "@Table", "TABLE_NAME", 3},
  1250. new object [] {"Columns", "Column", "@Column", "COLUMN_NAME", 4},
  1251. new object [] {"StructuredTypeMembers", "Catalog", "@Catalog", "TYPE_CATALOG", 1},
  1252. new object [] {"StructuredTypeMembers", "Owner", "@Owner", "TYPE_SCHEMA", 2},
  1253. new object [] {"StructuredTypeMembers", "Type", "@Type", "TYPE_NAME", 3},
  1254. new object [] {"StructuredTypeMembers", "Member", "@Member", "MEMBER_NAME", 4},
  1255. new object [] {"Views", "Catalog", "@Catalog", "TABLE_CATALOG", 1},
  1256. new object [] {"Views", "Owner", "@Owner", "TABLE_SCHEMA", 2},
  1257. new object [] {"Views", "Table", "@Table", "TABLE_NAME", 3},
  1258. new object [] {"ViewColumns", "Catalog", "@Catalog", "VIEW_CATALOG", 1},
  1259. new object [] {"ViewColumns", "Owner", "@Owner", "VIEW_SCHEMA", 2},
  1260. new object [] {"ViewColumns", "Table", "@Table", "VIEW_NAME", 3},
  1261. new object [] {"ViewColumns", "Column", "@Column", "COLUMN_NAME", 4},
  1262. new object [] {"ProcedureParameters", "Catalog", "@Catalog", "SPECIFIC_CATALOG", 1},
  1263. new object [] {"ProcedureParameters", "Owner", "@Owner", "SPECIFIC_SCHEMA", 2},
  1264. new object [] {"ProcedureParameters", "Name", "@Name", "SPECIFIC_NAME", 3},
  1265. new object [] {"ProcedureParameters", "Parameter", "@Parameter", "PARAMETER_NAME", 4},
  1266. new object [] {"Procedures", "Catalog", "@Catalog", "SPECIFIC_CATALOG", 1},
  1267. new object [] {"Procedures", "Owner", "@Owner", "SPECIFIC_SCHEMA", 2},
  1268. new object [] {"Procedures", "Name", "@Name", "SPECIFIC_NAME", 3},
  1269. new object [] {"Procedures", "Type", "@Type", "ROUTINE_TYPE", 4},
  1270. new object [] {"IndexColumns", "Catalog", "@Catalog", "db_name()", 1},
  1271. new object [] {"IndexColumns", "Owner", "@Owner", "user_name()", 2},
  1272. new object [] {"IndexColumns", "Table", "@Table", "o.name", 3},
  1273. new object [] {"IndexColumns", "ConstraintName", "@ConstraintName", "x.name", 4},
  1274. new object [] {"IndexColumns", "Column", "@Column", "c.name", 5},
  1275. new object [] {"Indexes", "Catalog", "@Catalog", "db_name()", 1},
  1276. new object [] {"Indexes", "Owner", "@Owner", "user_name()", 2},
  1277. new object [] {"Indexes", "Table", "@Table", "o.name", 3},
  1278. new object [] {"Indexes", "Name", "@Name", "x.name", 4},
  1279. new object [] {"UserDefinedTypes", "assembly_name", "@AssemblyName", "assemblies.name", 1},
  1280. new object [] {"UserDefinedTypes", "udt_name", "@UDTName", "types.assembly_class", 2},
  1281. new object [] {"ForeignKeys", "Catalog", "@Catalog", "CONSTRAINT_CATALOG", 1},
  1282. new object [] {"ForeignKeys", "Owner", "@Owner", "CONSTRAINT_SCHEMA", 2},
  1283. new object [] {"ForeignKeys", "Table", "@Table", "TABLE_NAME", 3},
  1284. new object [] {"ForeignKeys", "Name", "@Name", "CONSTRAINT_NAME", 4}
  1285. };
  1286. static DataTable instance;
  1287. static public DataTable Instance {
  1288. get {
  1289. if (instance == null) {
  1290. instance = new DataTable ("Restrictions");
  1291. foreach (ColumnInfo c in columns)
  1292. instance.Columns.Add (c.name, c.type);
  1293. foreach (object [] row in rows)
  1294. instance.LoadDataRow (row, true);
  1295. }
  1296. return instance;
  1297. }
  1298. }
  1299. }
  1300. public override DataTable GetSchema ()
  1301. {
  1302. if (state == ConnectionState.Closed)
  1303. throw ExceptionHelper.ConnectionClosed ();
  1304. return MetaDataCollections.Instance;
  1305. }
  1306. public override DataTable GetSchema (String collectionName)
  1307. {
  1308. return GetSchema (collectionName, null);
  1309. }
  1310. public override DataTable GetSchema (String collectionName, string [] restrictionValues)
  1311. {
  1312. // LAMESPEC: In MS.NET, if collectionName is null, it throws ArgumentException.
  1313. if (state == ConnectionState.Closed)
  1314. throw ExceptionHelper.ConnectionClosed ();
  1315. String cName = null;
  1316. DataTable schemaTable = MetaDataCollections.Instance;
  1317. int length = restrictionValues == null ? 0 : restrictionValues.Length;
  1318. foreach (DataRow row in schemaTable.Rows) {
  1319. if (String.Compare ((string) row["CollectionName"], collectionName, true) == 0) {
  1320. if (length > (int) row["NumberOfRestrictions"]) {
  1321. throw new ArgumentException ("More restrictions were provided " +
  1322. "than the requested schema ('" +
  1323. row["CollectionName"].ToString () + "') supports");
  1324. }
  1325. cName = row["CollectionName"].ToString();
  1326. }
  1327. }
  1328. if (cName == null)
  1329. throw new ArgumentException (string.Format (CultureInfo.InvariantCulture,
  1330. "The requested collection ({0}) is not defined.",
  1331. collectionName));
  1332. SqlCommand command = null;
  1333. DataTable dataTable = new DataTable ();
  1334. SqlDataAdapter dataAdapter = new SqlDataAdapter ();
  1335. switch (cName)
  1336. {
  1337. case "Databases":
  1338. command = new SqlCommand ("select name as database_name, dbid, crdate as create_date " +
  1339. "from master.sys.sysdatabases where (name = @Name or (@Name " +
  1340. "is null))", this);
  1341. command.Parameters.Add ("@Name", SqlDbType.NVarChar, 4000);
  1342. break;
  1343. case "ForeignKeys":
  1344. command = new SqlCommand ("select CONSTRAINT_CATALOG, CONSTRAINT_SCHEMA, CONSTRAINT_NAME, " +
  1345. "TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_TYPE, " +
  1346. "IS_DEFERRABLE, INITIALLY_DEFERRED from " +
  1347. "INFORMATION_SCHEMA.TABLE_CONSTRAINTS where (CONSTRAINT_CATALOG" +
  1348. " = @Catalog or (@Catalog is null)) and (CONSTRAINT_SCHEMA = " +
  1349. "@Owner or (@Owner is null)) and (TABLE_NAME = @Table or (" +
  1350. "@Table is null)) and (CONSTRAINT_NAME = @Name or (@Name is null))" +
  1351. " and CONSTRAINT_TYPE = 'FOREIGN KEY' order by CONSTRAINT_CATALOG," +
  1352. " CONSTRAINT_SCHEMA, CONSTRAINT_NAME", this);
  1353. command.Parameters.Add ("@Catalog", SqlDbType.NVarChar, 4000);
  1354. command.Parameters.Add ("@Owner", SqlDbType.NVarChar, 4000);
  1355. command.Parameters.Add ("@Table", SqlDbType.NVarChar, 4000);
  1356. command.Parameters.Add ("@Name", SqlDbType.NVarChar, 4000);
  1357. break;
  1358. case "Indexes":
  1359. command = new SqlCommand ("select distinct db_name() as constraint_catalog, " +
  1360. "constraint_schema = user_name (o.uid), " +
  1361. "constraint_name = x.name, table_catalog = db_name (), " +
  1362. "table_schema = user_name (o.uid), table_name = o.name, " +
  1363. "index_name = x.name from sysobjects o, sysindexes x, " +
  1364. "sysindexkeys xk where o.type in ('U') and x.id = o.id and " +
  1365. "o.id = xk.id and x.indid = xk.indid and xk.keyno = x.keycnt " +
  1366. "and (db_name() = @Catalog or (@Catalog is null)) and " +
  1367. "(user_name() = @Owner or (@Owner is null)) and (o.name = " +
  1368. "@Table or (@Table is null)) and (x.name = @Name or (@Name is null))" +
  1369. "order by table_name, index_name", this);
  1370. command.Parameters.Add ("@Catalog", SqlDbType.NVarChar, 4000);
  1371. command.Parameters.Add ("@Owner", SqlDbType.NVarChar, 4000);
  1372. command.Parameters.Add ("@Table", SqlDbType.NVarChar, 4000);
  1373. command.Parameters.Add ("@Name", SqlDbType.NVarChar, 4000);
  1374. break;
  1375. case "IndexColumns":
  1376. command = new SqlCommand ("select distinct db_name() as constraint_catalog, " +
  1377. "constraint_schema = user_name (o.uid), constraint_name = x.name, " +
  1378. "table_catalog = db_name (), table_schema = user_name (o.uid), " +
  1379. "table_name = o.name, column_name = c.name, " +
  1380. "ordinal_position = convert (int, xk.keyno), keyType = c.xtype, " +
  1381. "index_name = x.name from sysobjects o, sysindexes x, syscolumns c, " +
  1382. "sysindexkeys xk where o.type in ('U') and x.id = o.id and o.id = c.id " +
  1383. "and o.id = xk.id and x.indid = xk.indid and c.colid = xk.colid " +
  1384. "and xk.keyno <= x.keycnt and permissions (o.id, c.name) <> 0 " +
  1385. "and (db_name() = @Catalog or (@Catalog is null)) and (user_name() " +
  1386. "= @Owner or (@Owner is null)) and (o.name = @Table or (@Table is" +
  1387. " null)) and (x.name = @ConstraintName or (@ConstraintName is null)) " +
  1388. "and (c.name = @Column or (@Column is null)) order by table_name, " +
  1389. "index_name", this);
  1390. command.Parameters.Add ("@Catalog", SqlDbType.NVarChar, 8);
  1391. command.Parameters.Add ("@Owner", SqlDbType.NVarChar, 4000);
  1392. command.Parameters.Add ("@Table", SqlDbType.NVarChar, 13);
  1393. command.Parameters.Add ("@ConstraintName", SqlDbType.NVarChar, 4000);
  1394. command.Parameters.Add ("@Column", SqlDbType.NVarChar, 4000);
  1395. break;
  1396. case "Procedures":
  1397. command = new SqlCommand ("select SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME, " +
  1398. "ROUTINE_CATALOG, ROUTINE_SCHEMA, ROUTINE_NAME, ROUTINE_TYPE, " +
  1399. "CREATED, LAST_ALTERED from INFORMATION_SCHEMA.ROUTINES where " +
  1400. "(SPECIFIC_CATALOG = @Catalog or (@Catalog is null)) and " +
  1401. "(SPECIFIC_SCHEMA = @Owner or (@Owner is null)) and (SPECIFIC_NAME" +
  1402. " = @Name or (@Name is null)) and (ROUTINE_TYPE = @Type or (@Type " +
  1403. "is null)) order by SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME", this);
  1404. command.Parameters.Add ("@Catalog", SqlDbType.NVarChar, 4000);
  1405. command.Parameters.Add ("@Owner", SqlDbType.NVarChar, 4000);
  1406. command.Parameters.Add ("@Name", SqlDbType.NVarChar, 4000);
  1407. command.Parameters.Add ("@Type", SqlDbType.NVarChar, 4000);
  1408. break;
  1409. case "ProcedureParameters":
  1410. command = new SqlCommand ("select SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME, " +
  1411. "ORDINAL_POSITION, PARAMETER_MODE, IS_RESULT, AS_LOCATOR, " +
  1412. "PARAMETER_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, " +
  1413. "CHARACTER_OCTET_LENGTH, COLLATION_CATALOG, COLLATION_SCHEMA, " +
  1414. "COLLATION_NAME, CHARACTER_SET_CATALOG, CHARACTER_SET_SCHEMA, " +
  1415. "CHARACTER_SET_NAME, NUMERIC_PRECISION, NUMERIC_PRECISION_RADIX, " +
  1416. "NUMERIC_SCALE, DATETIME_PRECISION, INTERVAL_TYPE, " +
  1417. "INTERVAL_PRECISION from INFORMATION_SCHEMA.PARAMETERS where " +
  1418. "(SPECIFIC_CATALOG = @Catalog or (@Catalog is null)) and " +
  1419. "(SPECIFIC_SCHEMA = @Owner or (@Owner is null)) and (SPECIFIC_NAME = " +
  1420. "@Name or (@Name is null)) and (PARAMETER_NAME = @Parameter or (" +
  1421. "@Parameter is null)) order by SPECIFIC_CATALOG, SPECIFIC_SCHEMA," +
  1422. " SPECIFIC_NAME, PARAMETER_NAME", this);
  1423. command.Parameters.Add ("@Catalog", SqlDbType.NVarChar, 4000);
  1424. command.Parameters.Add ("@Owner", SqlDbType.NVarChar, 4000);
  1425. command.Parameters.Add ("@Name", SqlDbType.NVarChar, 4000);
  1426. command.Parameters.Add ("@Parameter", SqlDbType.NVarChar, 4000);
  1427. break;
  1428. case "Tables":
  1429. command = new SqlCommand ("select TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE " +
  1430. "from INFORMATION_SCHEMA.TABLES where" +
  1431. " (TABLE_CATALOG = @catalog or (@catalog is null)) and " +
  1432. "(TABLE_SCHEMA = @owner or (@owner is null))and " +
  1433. "(TABLE_NAME = @name or (@name is null)) and " +
  1434. "(TABLE_TYPE = @table_type or (@table_type is null))", this);
  1435. command.Parameters.Add ("@catalog", SqlDbType.NVarChar, 8);
  1436. command.Parameters.Add ("@owner", SqlDbType.NVarChar, 3);
  1437. command.Parameters.Add ("@name", SqlDbType.NVarChar, 11);
  1438. command.Parameters.Add ("@table_type", SqlDbType.NVarChar, 10);
  1439. break;
  1440. case "Columns":
  1441. command = new SqlCommand ("select TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, " +
  1442. "ORDINAL_POSITION, COLUMN_DEFAULT, IS_NULLABLE, DATA_TYPE, " +
  1443. "CHARACTER_MAXIMUM_LENGTH, CHARACTER_OCTET_LENGTH, " +
  1444. "NUMERIC_PRECISION, NUMERIC_PRECISION_RADIX, NUMERIC_SCALE, " +
  1445. "DATETIME_PRECISION, CHARACTER_SET_CATALOG, CHARACTER_SET_SCHEMA, " +
  1446. "CHARACTER_SET_NAME, COLLATION_CATALOG from INFORMATION_SCHEMA.COLUMNS" +
  1447. " where (TABLE_CATALOG = @Catalog or (@Catalog is null)) and (" +
  1448. "TABLE_SCHEMA = @Owner or (@Owner is null)) and (TABLE_NAME = @table" +
  1449. " or (@Table is null)) and (COLUMN_NAME = @column or (@Column is null" +
  1450. ")) order by TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME", this);
  1451. command.Parameters.Add ("@Catalog", SqlDbType.NVarChar, 4000);
  1452. command.Parameters.Add ("@Owner", SqlDbType.NVarChar, 4000);
  1453. command.Parameters.Add ("@Table", SqlDbType.NVarChar, 4000);
  1454. command.Parameters.Add ("@Column", SqlDbType.NVarChar, 4000);
  1455. break;
  1456. case "Users":
  1457. command = new SqlCommand ("select uid, name as user_name, createdate, updatedate from sysusers" +
  1458. " where (name = @Name or (@Name is null))", this);
  1459. command.Parameters.Add ("@Name", SqlDbType.NVarChar, 4000);
  1460. break;
  1461. case "StructuredTypeMembers":
  1462. // Only available on SQL Server 2008
  1463. // Running it again SQL 2005 results in the following exception:
  1464. // Unable to build the 'StructuredTypeMembers' collection because
  1465. // execution of the SQL query failed. See the inner exception for details.
  1466. // ---> System.Data.SqlClient.SqlException: Invalid object name 'sys.table_types'.
  1467. //
  1468. // I don't have access to SQL Server 2008 right now,
  1469. // and can't find any online documentation on the 'sys.table_types'
  1470. // view
  1471. throw new NotImplementedException ();
  1472. case "Views":
  1473. command = new SqlCommand ("select TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, CHECK_OPTION, " +
  1474. "IS_UPDATABLE from INFORMATION_SCHEMA.VIEWS where (TABLE_CATALOG" +
  1475. " = @Catalog or (@Catalog is null)) TABLE_SCHEMA = @Owner or " +
  1476. "(@Owner is null)) and (TABLE_NAME = @table or (@Table is null))" +
  1477. " order by TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME", this);
  1478. command.Parameters.Add ("@Catalog", SqlDbType.NVarChar, 4000);
  1479. command.Parameters.Add ("@Owner", SqlDbType.NVarChar, 4000);
  1480. command.Parameters.Add ("@Table", SqlDbType.NVarChar, 4000);
  1481. break;
  1482. case "ViewColumns":
  1483. command = new SqlCommand ("select VIEW_CATALOG, VIEW_SCHEMA, VIEW_NAME, TABLE_CATALOG, " +
  1484. "TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME from " +
  1485. "INFORMATION_SCHEMA.VIEW_COLUMN_USAGE where (VIEW_CATALOG = " +
  1486. "@Catalog (@Catalog is null)) and (VIEW_SCHEMA = @Owner (@Owner" +
  1487. " is null)) and (VIEW_NAME = @Table or (@Table is null)) and " +
  1488. "(COLUMN_NAME = @Column or (@Column is null)) order by " +
  1489. "VIEW_CATALOG, VIEW_SCHEMA, VIEW_NAME", this);
  1490. command.Parameters.Add ("@Catalog", SqlDbType.NVarChar, 4000);
  1491. command.Parameters.Add ("@Owner", SqlDbType.NVarChar, 4000);
  1492. command.Parameters.Add ("@Table", SqlDbType.NVarChar, 4000);
  1493. command.Parameters.Add ("@Column", SqlDbType.NVarChar, 4000);
  1494. break;
  1495. case "UserDefinedTypes":
  1496. command = new SqlCommand ("select assemblies.name as assembly_name, types.assembly_class " +
  1497. "as udt_name, ASSEMBLYPROPERTY(assemblies.name, 'VersionMajor') " +
  1498. "as version_major, ASSEMBLYPROPERTY(assemblies.name, 'VersionMinor') " +
  1499. "as version_minor, ASSEMBLYPROPERTY(assemblies.name, 'VersionBuild') " +
  1500. "as version_build, ASSEMBLYPROPERTY(assemblies.name, 'VersionRevision') " +
  1501. "as version_revision, ASSEMBLYPROPERTY(assemblies.name, 'CultureInfo') " +
  1502. "as culture_info, ASSEMBLYPROPERTY(assemblies.name, 'PublicKey') " +
  1503. "as public_key, is_fixed_length, max_length, Create_Date, " +
  1504. "Permission_set_desc from sys.assemblies as assemblies join " +
  1505. "sys.assembly_types as types on assemblies.assembly_id = types.assembly_id" +
  1506. " where (assportemblies.name = @AssemblyName or (@AssemblyName is null)) and " +
  1507. "(types.assembly_class = @UDTName or (@UDTName is null))",
  1508. this);
  1509. command.Parameters.Add ("@AssemblyName", SqlDbType.NVarChar, 4000);
  1510. command.Parameters.Add ("@UDTName", SqlDbType.NVarChar, 4000);
  1511. break;
  1512. case "MetaDataCollections":
  1513. return MetaDataCollections.Instance;
  1514. case "DataSourceInformation":
  1515. return DataSourceInformation.GetInstance (this);
  1516. case "DataTypes":
  1517. return DataTypes.Instance;
  1518. case "ReservedWords":
  1519. return ReservedWords.Instance;
  1520. case "Restrictions":
  1521. return Restrictions.Instance;
  1522. }
  1523. for (int i = 0; i < length; i++) {
  1524. command.Parameters[i].Value = restrictionValues[i];
  1525. }
  1526. dataAdapter.SelectCommand = command;
  1527. dataAdapter.Fill (dataTable);
  1528. return dataTable;
  1529. }
  1530. public static void ChangePassword (string connectionString, string newPassword)
  1531. {
  1532. if (String.IsNullOrEmpty (connectionString))
  1533. throw new ArgumentNullException ("The 'connectionString' cannot be null or empty.");
  1534. if (String.IsNullOrEmpty (newPassword))
  1535. throw new ArgumentNullException ("The 'newPassword' cannot be null or empty.");
  1536. if (newPassword.Length > 128)
  1537. throw new ArgumentException ("The length of 'newPassword' cannot exceed 128 characters.");
  1538. using (SqlConnection conn = new SqlConnection (connectionString)) {
  1539. conn.Open ();
  1540. conn.tds.Execute (String.Format ("sp_password '{0}', '{1}', '{2}'",
  1541. conn.parms.Password, newPassword, conn.parms.User));
  1542. }
  1543. }
  1544. public static void ClearAllPools ()
  1545. {
  1546. // FIXME: locking
  1547. IDictionary pools = SqlConnection.sqlConnectionPools.GetConnectionPool ();
  1548. foreach (TdsConnectionPool pool in pools.Values) {
  1549. if (pool != null)
  1550. pool.ResetConnectionPool ();
  1551. }
  1552. pools.Clear ();
  1553. }
  1554. public static void ClearPool (SqlConnection connection)
  1555. {
  1556. if (connection == null)
  1557. throw new ArgumentNullException ("connection");
  1558. // FIXME: locking
  1559. if (connection.pooling) {
  1560. TdsConnectionPool pool = sqlConnectionPools.GetConnectionPool (connection.ConnectionString);
  1561. if (pool != null)
  1562. pool.ResetConnectionPool ();
  1563. }
  1564. }
  1565. #endif // NET_2_0
  1566. #endregion // Methods
  1567. #if NET_2_0
  1568. #region Fields Net 2
  1569. bool async;
  1570. bool userInstance;
  1571. #endregion // Fields Net 2
  1572. #region Properties Net 2
  1573. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  1574. internal bool AsyncProcessing {
  1575. get { return async; }
  1576. }
  1577. #endregion // Properties Net 2
  1578. #endif // NET_2_0
  1579. }
  1580. }