OdbcConnection.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. //
  2. // System.Data.Odbc.OdbcConnection
  3. //
  4. // Authors:
  5. // Brian Ritchie ([email protected])
  6. //
  7. // Copyright (C) Brian Ritchie, 2002
  8. //
  9. //
  10. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System.Collections;
  32. using System.ComponentModel;
  33. using System.Data;
  34. using System.Data.Common;
  35. using System.EnterpriseServices;
  36. using System.Runtime.InteropServices;
  37. using System.Text;
  38. #if NET_2_0
  39. using System.Transactions;
  40. #endif
  41. namespace System.Data.Odbc
  42. {
  43. [DefaultEvent ("InfoMessage")]
  44. #if NET_2_0
  45. public sealed class OdbcConnection : DbConnection, ICloneable
  46. #else
  47. public sealed class OdbcConnection : Component, ICloneable, IDbConnection
  48. #endif //NET_2_0
  49. {
  50. #region Fields
  51. string connectionString;
  52. int connectionTimeout;
  53. internal OdbcTransaction transaction;
  54. IntPtr henv = IntPtr.Zero;
  55. IntPtr hdbc = IntPtr.Zero;
  56. bool disposed;
  57. ArrayList linkedCommands;
  58. #endregion
  59. #region Constructors
  60. public OdbcConnection () : this (String.Empty)
  61. {
  62. }
  63. public OdbcConnection (string connectionString)
  64. {
  65. connectionTimeout = 15;
  66. ConnectionString = connectionString;
  67. }
  68. #endregion // Constructors
  69. #region Properties
  70. internal IntPtr hDbc {
  71. get { return hdbc; }
  72. }
  73. internal object Generation {
  74. // We use the linkedCommands array as a generation indicator for statement
  75. // handles allocated in our subsiduary OdbcCommands. The rule is that the
  76. // statement handles are only valid if the generation matches the one
  77. // returned when the command was linked to the connection.
  78. get { return linkedCommands; }
  79. }
  80. [OdbcCategoryAttribute ("DataCategory_Data")]
  81. [DefaultValue ("")]
  82. [OdbcDescriptionAttribute ("Information used to connect to a Data Source")]
  83. [RefreshPropertiesAttribute (RefreshProperties.All)]
  84. [EditorAttribute ("Microsoft.VSDesigner.Data.Odbc.Design.OdbcConnectionStringEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  85. [RecommendedAsConfigurableAttribute (true)]
  86. public
  87. #if NET_2_0
  88. override
  89. #endif
  90. string ConnectionString {
  91. get {
  92. if (connectionString == null)
  93. return string.Empty;
  94. return connectionString;
  95. }
  96. set { connectionString = value; }
  97. }
  98. [OdbcDescriptionAttribute ("Current connection timeout value, not settable in the ConnectionString")]
  99. [DefaultValue (15)]
  100. #if NET_2_0
  101. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  102. #endif
  103. public
  104. #if NET_2_0
  105. new
  106. #endif // NET_2_0
  107. int ConnectionTimeout {
  108. get {
  109. return connectionTimeout;
  110. }
  111. set {
  112. if (value < 0)
  113. throw new ArgumentException("Timout should not be less than zero.");
  114. connectionTimeout = value;
  115. }
  116. }
  117. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  118. [OdbcDescriptionAttribute ("Current data source Catlog value, 'Database=X' in the ConnectionString")]
  119. public
  120. #if NET_2_0
  121. override
  122. #endif // NET_2_0
  123. string Database {
  124. get {
  125. if (State == ConnectionState.Closed)
  126. return string.Empty;
  127. return GetInfo (OdbcInfo.DatabaseName);
  128. }
  129. }
  130. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  131. [OdbcDescriptionAttribute ("The ConnectionState indicating whether the connection is open or closed")]
  132. [BrowsableAttribute (false)]
  133. public
  134. #if NET_2_0
  135. override
  136. #endif // NET_2_0
  137. ConnectionState State {
  138. get {
  139. if (hdbc != IntPtr.Zero)
  140. return ConnectionState.Open;
  141. return ConnectionState.Closed;
  142. }
  143. }
  144. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  145. [OdbcDescriptionAttribute ("Current data source, 'Server=X' in the ConnectionString")]
  146. #if NET_2_0
  147. [Browsable (false)]
  148. #endif
  149. public
  150. #if NET_2_0
  151. override
  152. #endif // NET_2_0
  153. string DataSource {
  154. get {
  155. if (State == ConnectionState.Closed)
  156. return string.Empty;
  157. return GetInfo (OdbcInfo.DataSourceName);
  158. }
  159. }
  160. #if NET_2_0
  161. [Browsable (false)]
  162. #endif
  163. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  164. [OdbcDescriptionAttribute ("Current ODBC Driver")]
  165. public string Driver {
  166. get {
  167. if (State == ConnectionState.Closed)
  168. return string.Empty;
  169. return GetInfo (OdbcInfo.DriverName);
  170. }
  171. }
  172. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  173. [OdbcDescriptionAttribute ("Version of the product accessed by the ODBC Driver")]
  174. [BrowsableAttribute (false)]
  175. public
  176. #if NET_2_0
  177. override
  178. #endif // NET_2_0
  179. string ServerVersion {
  180. get {
  181. return GetInfo (OdbcInfo.DbmsVersion);
  182. }
  183. }
  184. internal string SafeDriver {
  185. get {
  186. string driver_name = GetSafeInfo (OdbcInfo.DriverName);
  187. if (driver_name == null)
  188. return string.Empty;
  189. return driver_name;
  190. }
  191. }
  192. #endregion // Properties
  193. #region Methods
  194. public
  195. #if NET_2_0
  196. new
  197. #endif // NET_2_0
  198. OdbcTransaction BeginTransaction ()
  199. {
  200. return BeginTransaction (IsolationLevel.Unspecified);
  201. }
  202. #if ONLY_1_1
  203. IDbTransaction IDbConnection.BeginTransaction ()
  204. {
  205. return (IDbTransaction) BeginTransaction ();
  206. }
  207. #endif // ONLY_1_1
  208. #if NET_2_0
  209. protected override DbTransaction BeginDbTransaction (IsolationLevel isolationLevel)
  210. {
  211. return BeginTransaction (isolationLevel);
  212. }
  213. #endif
  214. public
  215. #if NET_2_0
  216. new
  217. #endif // NET_2_0
  218. OdbcTransaction BeginTransaction (IsolationLevel isolevel)
  219. {
  220. if (State == ConnectionState.Closed)
  221. throw ExceptionHelper.ConnectionClosed ();
  222. if (transaction == null) {
  223. transaction = new OdbcTransaction (this, isolevel);
  224. return transaction;
  225. } else
  226. throw new InvalidOperationException ();
  227. }
  228. #if ONLY_1_1
  229. IDbTransaction IDbConnection.BeginTransaction (IsolationLevel isolevel)
  230. {
  231. return (IDbTransaction) BeginTransaction (isolevel);
  232. }
  233. #endif // ONLY_1_1
  234. public
  235. #if NET_2_0
  236. override
  237. #endif // NET_2_0
  238. void Close ()
  239. {
  240. OdbcReturn ret = OdbcReturn.Error;
  241. if (State == ConnectionState.Open) {
  242. lock(this) {
  243. // close any associated commands
  244. // NOTE: we may 'miss' some if the garbage collector has
  245. // already started to destroy them.
  246. if (linkedCommands != null) {
  247. for (int i = 0; i < linkedCommands.Count; i++) {
  248. WeakReference wr = (WeakReference) linkedCommands [i];
  249. if (wr == null)
  250. continue;
  251. OdbcCommand c = (OdbcCommand) wr.Target;
  252. if (c != null)
  253. c.Unlink ();
  254. }
  255. linkedCommands = null;
  256. }
  257. // disconnect
  258. ret = libodbc.SQLDisconnect (hdbc);
  259. }
  260. // There could be OdbcCommands outstanding (see NOTE above); their
  261. // hstmts will have been freed and therefore will be invalid.
  262. // However, they will find that their definition of Generation
  263. // does not match the connection's, so they won't try and free
  264. // those hstmt.
  265. if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
  266. throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
  267. FreeHandles ();
  268. transaction = null;
  269. RaiseStateChange (ConnectionState.Open, ConnectionState.Closed);
  270. }
  271. }
  272. public
  273. #if NET_2_0
  274. new
  275. #endif // NET_2_0
  276. OdbcCommand CreateCommand ()
  277. {
  278. return new OdbcCommand (string.Empty, this, transaction);
  279. }
  280. public
  281. #if NET_2_0
  282. override
  283. #endif // NET_2_0
  284. void ChangeDatabase (string value)
  285. {
  286. IntPtr ptr = IntPtr.Zero;
  287. OdbcReturn ret = OdbcReturn.Error;
  288. try {
  289. ptr = Marshal.StringToHGlobalUni (value);
  290. ret = libodbc.SQLSetConnectAttr (hdbc, OdbcConnectionAttribute.CurrentCatalog, ptr, value.Length * 2);
  291. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  292. throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
  293. } finally {
  294. if (ptr != IntPtr.Zero)
  295. Marshal.FreeCoTaskMem (ptr);
  296. }
  297. }
  298. protected override void Dispose (bool disposing)
  299. {
  300. if (!this.disposed) {
  301. try {
  302. // release the native unmananged resources
  303. this.Close ();
  304. this.disposed = true;
  305. } finally {
  306. // call Dispose on the base class
  307. base.Dispose (disposing);
  308. }
  309. }
  310. }
  311. [MonoTODO]
  312. object ICloneable.Clone ()
  313. {
  314. throw new NotImplementedException ();
  315. }
  316. #if ONLY_1_1
  317. IDbCommand IDbConnection.CreateCommand ()
  318. {
  319. return (IDbCommand) CreateCommand ();
  320. }
  321. #endif //ONLY_1_1
  322. #if NET_2_0
  323. protected override DbCommand CreateDbCommand ()
  324. {
  325. return CreateCommand ();
  326. }
  327. #endif
  328. public
  329. #if NET_2_0
  330. override
  331. #endif // NET_2_0
  332. void Open ()
  333. {
  334. if (State == ConnectionState.Open)
  335. throw new InvalidOperationException ();
  336. OdbcReturn ret = OdbcReturn.Error;
  337. OdbcException e = null;
  338. try {
  339. // allocate Environment handle
  340. ret = libodbc.SQLAllocHandle (OdbcHandleType.Env, IntPtr.Zero, ref henv);
  341. if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo)) {
  342. OdbcErrorCollection errors = new OdbcErrorCollection ();
  343. errors.Add (new OdbcError (SafeDriver, "Error in " + SafeDriver, "", 1));
  344. e = new OdbcException (errors);
  345. MessageHandler (e);
  346. throw e;
  347. }
  348. ret = libodbc.SQLSetEnvAttr (henv, OdbcEnv.OdbcVersion, (IntPtr) libodbc.SQL_OV_ODBC3 , 0);
  349. if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
  350. throw CreateOdbcException (OdbcHandleType.Env, henv);
  351. // allocate connection handle
  352. ret = libodbc.SQLAllocHandle (OdbcHandleType.Dbc, henv, ref hdbc);
  353. if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
  354. throw CreateOdbcException (OdbcHandleType.Env, henv);
  355. // DSN connection
  356. if (ConnectionString.ToLower ().IndexOf ("dsn=") >= 0) {
  357. string _uid = string.Empty, _pwd = string.Empty, _dsn = string.Empty;
  358. string [] items = ConnectionString.Split (new char[1] {';'});
  359. foreach (string item in items)
  360. {
  361. string [] parts = item.Split (new char[1] {'='});
  362. switch (parts [0].Trim ().ToLower ()) {
  363. case "dsn":
  364. _dsn = parts [1].Trim ();
  365. break;
  366. case "uid":
  367. _uid = parts [1].Trim ();
  368. break;
  369. case "pwd":
  370. _pwd = parts [1].Trim ();
  371. break;
  372. }
  373. }
  374. ret = libodbc.SQLConnect(hdbc, _dsn, -3, _uid, -3, _pwd, -3);
  375. if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
  376. throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
  377. } else {
  378. // DSN-less Connection
  379. string OutConnectionString = new String (' ',1024);
  380. short OutLen = 0;
  381. ret = libodbc.SQLDriverConnect (hdbc, IntPtr.Zero, ConnectionString, -3,
  382. OutConnectionString, (short) OutConnectionString.Length, ref OutLen, 0);
  383. if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
  384. throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
  385. }
  386. RaiseStateChange (ConnectionState.Closed, ConnectionState.Open);
  387. } catch {
  388. // free handles if any.
  389. FreeHandles ();
  390. throw;
  391. }
  392. disposed = false;
  393. }
  394. [MonoTODO]
  395. public static void ReleaseObjectPool ()
  396. {
  397. throw new NotImplementedException ();
  398. }
  399. private void FreeHandles ()
  400. {
  401. OdbcReturn ret = OdbcReturn.Error;
  402. if (hdbc != IntPtr.Zero) {
  403. ret = libodbc.SQLFreeHandle ((ushort) OdbcHandleType.Dbc, hdbc);
  404. if ( (ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
  405. throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
  406. }
  407. hdbc = IntPtr.Zero;
  408. if (henv != IntPtr.Zero) {
  409. ret = libodbc.SQLFreeHandle ((ushort) OdbcHandleType.Env, henv);
  410. if ( (ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
  411. throw CreateOdbcException (OdbcHandleType.Env, henv);
  412. }
  413. henv = IntPtr.Zero;
  414. }
  415. #if NET_2_0
  416. public override DataTable GetSchema ()
  417. {
  418. if (State == ConnectionState.Closed)
  419. throw ExceptionHelper.ConnectionClosed ();
  420. return MetaDataCollections.Instance;
  421. }
  422. public override DataTable GetSchema (string collectionName)
  423. {
  424. return GetSchema (collectionName, null);
  425. }
  426. public override DataTable GetSchema (string collectionName, string [] restrictionValues)
  427. {
  428. if (State == ConnectionState.Closed)
  429. throw ExceptionHelper.ConnectionClosed ();
  430. return GetSchema (collectionName, null);
  431. }
  432. [MonoTODO]
  433. public override void EnlistTransaction (Transaction transaction)
  434. {
  435. throw new NotImplementedException ();
  436. }
  437. #endif
  438. [MonoTODO]
  439. public void EnlistDistributedTransaction (ITransaction transaction)
  440. {
  441. throw new NotImplementedException ();
  442. }
  443. internal string GetInfo (OdbcInfo info)
  444. {
  445. if (State == ConnectionState.Closed)
  446. throw new InvalidOperationException ("The connection is closed.");
  447. OdbcReturn ret = OdbcReturn.Error;
  448. short max_length = 512;
  449. byte [] buffer = new byte [512];
  450. short actualLength = 0;
  451. ret = libodbc.SQLGetInfo (hdbc, info, buffer, max_length, ref actualLength);
  452. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  453. throw CreateOdbcException (OdbcHandleType.Dbc, hdbc);
  454. return Encoding.Unicode.GetString (buffer, 0, actualLength);
  455. }
  456. string GetSafeInfo (OdbcInfo info)
  457. {
  458. if (State == ConnectionState.Closed)
  459. return null;
  460. OdbcReturn ret = OdbcReturn.Error;
  461. short max_length = 512;
  462. byte [] buffer = new byte [512];
  463. short actualLength = 0;
  464. ret = libodbc.SQLGetInfo (hdbc, info, buffer, max_length, ref actualLength);
  465. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  466. return null;
  467. return Encoding.Unicode.GetString (buffer, 0, actualLength);
  468. }
  469. private void RaiseStateChange (ConnectionState from, ConnectionState to)
  470. {
  471. #if ONLY_1_1
  472. if (StateChange != null)
  473. StateChange (this, new StateChangeEventArgs (from, to));
  474. #else
  475. base.OnStateChange (new StateChangeEventArgs (from, to));
  476. #endif
  477. }
  478. private OdbcInfoMessageEventArgs CreateOdbcInfoMessageEvent (OdbcErrorCollection errors)
  479. {
  480. return new OdbcInfoMessageEventArgs (errors);
  481. }
  482. private void OnOdbcInfoMessage (OdbcInfoMessageEventArgs e)
  483. {
  484. if (InfoMessage != null)
  485. InfoMessage (this, e);
  486. }
  487. internal OdbcException CreateOdbcException (OdbcHandleType HandleType, IntPtr Handle)
  488. {
  489. short buflen = 256;
  490. short txtlen = 0;
  491. int nativeerror = 0;
  492. OdbcReturn ret = OdbcReturn.Success;
  493. OdbcErrorCollection errors = new OdbcErrorCollection ();
  494. while (true) {
  495. byte [] buf_MsgText = new byte [buflen * 2];
  496. byte [] buf_SqlState = new byte [buflen * 2];
  497. switch (HandleType) {
  498. case OdbcHandleType.Dbc:
  499. ret = libodbc.SQLError (IntPtr.Zero, Handle, IntPtr.Zero, buf_SqlState,
  500. ref nativeerror, buf_MsgText, buflen, ref txtlen);
  501. break;
  502. case OdbcHandleType.Stmt:
  503. ret = libodbc.SQLError (IntPtr.Zero, IntPtr.Zero, Handle, buf_SqlState,
  504. ref nativeerror, buf_MsgText, buflen, ref txtlen);
  505. break;
  506. case OdbcHandleType.Env:
  507. ret = libodbc.SQLError (Handle, IntPtr.Zero, IntPtr.Zero, buf_SqlState,
  508. ref nativeerror, buf_MsgText, buflen, ref txtlen);
  509. break;
  510. }
  511. if (ret != OdbcReturn.Success)
  512. break;
  513. string state = RemoveTrailingNullChar (Encoding.Unicode.GetString (buf_SqlState));
  514. string message = Encoding.Unicode.GetString (buf_MsgText, 0, txtlen * 2);
  515. errors.Add (new OdbcError (SafeDriver, message, state, nativeerror));
  516. }
  517. string source = SafeDriver;
  518. foreach (OdbcError error in errors)
  519. error.SetSource (source);
  520. return new OdbcException (errors);
  521. }
  522. static string RemoveTrailingNullChar (string value)
  523. {
  524. return value.TrimEnd ('\0');
  525. }
  526. internal object Link (OdbcCommand cmd)
  527. {
  528. lock(this) {
  529. if (linkedCommands == null)
  530. linkedCommands = new ArrayList ();
  531. linkedCommands.Add (new WeakReference (cmd));
  532. return linkedCommands;
  533. }
  534. }
  535. internal object Unlink (OdbcCommand cmd)
  536. {
  537. lock(this) {
  538. if (linkedCommands == null)
  539. return null;
  540. for (int i = 0; i < linkedCommands.Count; i++) {
  541. WeakReference wr = (WeakReference) linkedCommands [i];
  542. if (wr == null)
  543. continue;
  544. OdbcCommand c = (OdbcCommand) wr.Target;
  545. if (c == cmd) {
  546. linkedCommands [i] = null;
  547. break;
  548. }
  549. }
  550. return linkedCommands;
  551. }
  552. }
  553. #endregion
  554. #region Events and Delegates
  555. #if ONLY_1_1
  556. [OdbcDescription ("DbConnection_StateChange")]
  557. [OdbcCategory ("DataCategory_StateChange")]
  558. public event StateChangeEventHandler StateChange;
  559. #endif // ONLY_1_1
  560. [OdbcDescription ("DbConnection_InfoMessage")]
  561. [OdbcCategory ("DataCategory_InfoMessage")]
  562. public event OdbcInfoMessageEventHandler InfoMessage;
  563. private void MessageHandler (OdbcException e)
  564. {
  565. OnOdbcInfoMessage (CreateOdbcInfoMessageEvent (e.Errors));
  566. }
  567. #endregion
  568. }
  569. }