SqlConnection.cs 64 KB

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