SqlConnection.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. //
  2. // System.Data.SqlClient.SqlConnection.cs
  3. //
  4. // Author:
  5. // Rodrigo Moya ([email protected])
  6. // Daniel Morgan ([email protected])
  7. //
  8. // (C) Ximian, Inc 2002
  9. // (C) Daniel Morgan 2002
  10. //
  11. // Credits:
  12. // SQL and concepts were used from libgda 0.8.190 (GNOME Data Access)
  13. // http://www.gnome-db.org/
  14. // with permission from the authors of the
  15. // PostgreSQL provider in libgda:
  16. // Michael Lausch <[email protected]>
  17. // Rodrigo Moya <[email protected]>
  18. // Vivien Malerba <[email protected]>
  19. // Gonzalo Paniagua Javier <[email protected]>
  20. //
  21. // use #define DEBUG_SqlConnection if you want to spew debug messages
  22. // #define DEBUG_SqlConnection
  23. using System;
  24. using System.Collections;
  25. using System.ComponentModel;
  26. using System.Data;
  27. using System.Data.Common;
  28. using System.Runtime.InteropServices;
  29. using System.Text;
  30. namespace System.Data.SqlClient {
  31. // using PGconn = IntPtr;
  32. // PGconn is native C library type in libpq for Postgres Connection
  33. // using PGressult = IntPtr;
  34. // PGresult is native C library type in libpq for Postgres Resultset
  35. /// <summary>
  36. /// Represents an open connection to a SQL data source
  37. /// </summary>
  38. //public sealed class SqlConnection : Component, IDbConnection,
  39. // ICloneable
  40. public sealed class SqlConnection : IDbConnection {
  41. // FIXME: Need to implement class Component,
  42. // and interfaces: ICloneable and IDisposable
  43. #region Fields
  44. private PostgresTypes types;
  45. private IntPtr pgConn = IntPtr.Zero;
  46. // PGConn (Postgres Connection)
  47. private string connectionString = "";
  48. // OLE DB Connection String
  49. private string pgConnectionString = "";
  50. // PostgreSQL Connection String
  51. private SqlTransaction trans = null;
  52. private int connectionTimeout = 15;
  53. // default for 15 seconds
  54. // connection parameters in connection string
  55. private string host = "";
  56. // Name of host to connect to
  57. private string hostaddr = "";
  58. // IP address of host to connect to
  59. // should be in "n.n.n.n" format
  60. private string port = "";
  61. // Port number to connect to at the server host
  62. private string dbname = ""; // The database name.
  63. private string user = ""; // User name to connect as.
  64. private string password = "";
  65. // Password to be used if the server
  66. // demands password authentication.
  67. private string options = "";
  68. // Trace/debug options to be sent to the server.
  69. private string tty = "";
  70. // A file or tty for optional
  71. // debug output from the backend.
  72. private string requiressl = "";
  73. // Set to 1 to require
  74. // SSL connection to the backend.
  75. // Libpq will then refuse to connect
  76. // if the server does not
  77. // support SSL. Set to 0 (default) to
  78. // negotiate with server.
  79. private ConnectionState conState = ConnectionState.Closed;
  80. private bool dataReaderOpen = false;
  81. // FIXME: if true, throw an exception if SqlConnection
  82. // is used used for anything other than reading
  83. // data using SqlDataReader
  84. #endregion // Fields
  85. #region Constructors
  86. /*
  87. [MonoTODO]
  88. public SqlConnection ()
  89. {
  90. this.ConnectionString = null;
  91. this.ConnectionTimeout = 0;
  92. this.Database = null;
  93. this.State = 0;
  94. }
  95. [MonoTODO]
  96. public SqlConnection (string cs) : SqlConnection ()
  97. {
  98. this.ConnectionString = cs;
  99. }
  100. */
  101. // A lot of the defaults were initialized in the Fields
  102. [MonoTODO]
  103. public SqlConnection () {
  104. }
  105. [MonoTODO]
  106. public SqlConnection (String connectionString) {
  107. SetConnectionString (connectionString);
  108. }
  109. #endregion // Constructors
  110. #region Destructors
  111. [MonoTODO]
  112. public void Dispose () {
  113. // FIXME: release resources properly
  114. Close ();
  115. // Dispose (true);
  116. }
  117. // aka Finalize
  118. // [ClassInterface(ClassInterfaceType.AutoDual)]
  119. [MonoTODO]
  120. ~SqlConnection() {
  121. // FIXME: this class need
  122. // a destructor to release resources
  123. // Also, take a look at Dispose
  124. // Dispose (false);
  125. }
  126. #endregion // Destructors
  127. #region Public Methods
  128. IDbTransaction IDbConnection.BeginTransaction () {
  129. return BeginTransaction ();
  130. }
  131. public SqlTransaction BeginTransaction () {
  132. return TransactionBegin (); // call private method
  133. }
  134. IDbTransaction IDbConnection.BeginTransaction (IsolationLevel
  135. il) {
  136. return BeginTransaction (il);
  137. }
  138. public SqlTransaction BeginTransaction (IsolationLevel il) {
  139. return TransactionBegin (il); // call private method
  140. }
  141. // PostgreSQL does not support named transactions/savepoint
  142. // nor nested transactions
  143. [Obsolete]
  144. public SqlTransaction BeginTransaction(string transactionName) {
  145. return TransactionBegin (); // call private method
  146. }
  147. [Obsolete]
  148. public SqlTransaction BeginTransaction(IsolationLevel iso,
  149. string transactionName) {
  150. return TransactionBegin (iso); // call private method
  151. }
  152. [MonoTODO]
  153. public void ChangeDatabase (string databaseName) {
  154. throw new NotImplementedException ();
  155. }
  156. [MonoTODO]
  157. public void Close () {
  158. CloseDataSource ();
  159. }
  160. IDbCommand IDbConnection.CreateCommand () {
  161. return CreateCommand ();
  162. }
  163. public SqlCommand CreateCommand () {
  164. SqlCommand sqlcmd = new SqlCommand ("", this);
  165. return sqlcmd;
  166. }
  167. [MonoTODO]
  168. public void Open () {
  169. OpenDataSource ();
  170. }
  171. #endregion // Public Methods
  172. #region Protected Methods
  173. // FIXME: protected override void Dispose overrides Component
  174. // however, including Component causes other problems
  175. /*
  176. [MonoTODO]
  177. protected override void Dispose (bool disposing)
  178. {
  179. throw new NotImplementedException ();
  180. }
  181. */
  182. #endregion
  183. #region Private Methods
  184. private void OpenDataSource () {
  185. if(dbname.Equals(""))
  186. throw new InvalidOperationException(
  187. "dbname missing");
  188. else if(conState == ConnectionState.Open)
  189. throw new InvalidOperationException(
  190. "ConnnectionState is already Open");
  191. ConnStatusType connStatus;
  192. // FIXME: check to make sure we have
  193. // everything to connect,
  194. // otherwise, throw an exception
  195. pgConn = PostgresLibrary.PQconnectdb
  196. (pgConnectionString);
  197. // FIXME: should we use PQconnectStart/PQconnectPoll
  198. // instead of PQconnectdb?
  199. // PQconnectdb blocks
  200. // PQconnectStart/PQconnectPoll is non-blocking
  201. connStatus = PostgresLibrary.PQstatus (pgConn);
  202. if(connStatus == ConnStatusType.CONNECTION_OK) {
  203. // Successfully Connected
  204. conState = ConnectionState.Open;
  205. // FIXME: load types into hashtable
  206. types = new PostgresTypes(this);
  207. types.Load();
  208. }
  209. else {
  210. String errorMessage = PostgresLibrary.
  211. PQerrorMessage (pgConn);
  212. errorMessage += ": Could not connect to database.";
  213. throw new SqlException(0, 0,
  214. errorMessage, 0, "",
  215. host, "SqlConnection", 0);
  216. }
  217. }
  218. private void CloseDataSource () {
  219. // FIXME: just a quick hack
  220. conState = ConnectionState.Closed;
  221. PostgresLibrary.PQfinish (pgConn);
  222. }
  223. private void SetConnectionString (string connectionString) {
  224. // FIXME: perform error checking on string
  225. // while translating string from
  226. // OLE DB format to PostgreSQL
  227. // connection string format
  228. //
  229. // OLE DB: "host=localhost;dbname=test;user=joe;password=smoe"
  230. // PostgreSQL: "host=localhost dbname=test user=joe password=smoe"
  231. //
  232. // For OLE DB, you would have the additional
  233. // "provider=postgresql"
  234. // OleDbConnection you would be using libgda, maybe
  235. // it would be
  236. // "provider=OAFIID:GNOME_Database_Postgres_Provider"
  237. // instead.
  238. //
  239. // Also, parse the connection string into properties
  240. // FIXME: if connection is open, you can
  241. // not set the connection
  242. // string, throw an exception
  243. this.connectionString = connectionString;
  244. pgConnectionString = ConvertStringToPostgres (
  245. connectionString);
  246. #if DEBUG_SqlConnection
  247. Console.WriteLine(
  248. "OLE-DB Connection String [in]: " +
  249. this.ConnectionString);
  250. Console.WriteLine(
  251. "Postgres Connection String [out]: " +
  252. pgConnectionString);
  253. #endif // DEBUG_SqlConnection
  254. }
  255. private String ConvertStringToPostgres (String
  256. oleDbConnectionString) {
  257. StringBuilder postgresConnection =
  258. new StringBuilder();
  259. string result;
  260. string[] connectionParameters;
  261. char[] semicolon = new Char[1];
  262. semicolon[0] = ';';
  263. // FIXME: what is the max number of value pairs
  264. // can there be for the OLE DB
  265. // connnection string? what about libgda max?
  266. // what about postgres max?
  267. // FIXME: currently assuming value pairs are like:
  268. // "key1=value1;key2=value2;key3=value3"
  269. // Need to deal with values that have
  270. // single or double quotes. And error
  271. // handling of that too.
  272. // "key1=value1;key2='value2';key=\"value3\""
  273. // FIXME: put the connection parameters
  274. // from the connection
  275. // string into a
  276. // Hashtable (System.Collections)
  277. // instead of using private variables
  278. // to store them
  279. connectionParameters = oleDbConnectionString.
  280. Split (semicolon);
  281. foreach (string sParameter in connectionParameters) {
  282. if(sParameter.Length > 0) {
  283. BreakConnectionParameter (sParameter);
  284. postgresConnection.
  285. Append (sParameter +
  286. " ");
  287. }
  288. }
  289. result = postgresConnection.ToString ();
  290. return result;
  291. }
  292. private bool BreakConnectionParameter (String sParameter) {
  293. bool addParm = true;
  294. int index;
  295. index = sParameter.IndexOf ("=");
  296. if (index > 0) {
  297. string parmKey, parmValue;
  298. // separate string "key=value" to
  299. // string "key" and "value"
  300. parmKey = sParameter.Substring (0, index);
  301. parmValue = sParameter.Substring (index + 1,
  302. sParameter.Length - index - 1);
  303. switch(parmKey.ToLower()) {
  304. case "hostaddr":
  305. hostaddr = parmValue;
  306. break;
  307. case "port":
  308. port = parmValue;
  309. break;
  310. case "host":
  311. // set DataSource property
  312. host = parmValue;
  313. break;
  314. case "dbname":
  315. // set Database property
  316. dbname = parmValue;
  317. break;
  318. case "user":
  319. user = parmValue;
  320. break;
  321. case "password":
  322. password = parmValue;
  323. // addParm = false;
  324. break;
  325. case "options":
  326. options = parmValue;
  327. break;
  328. case "tty":
  329. tty = parmValue;
  330. break;
  331. case "requiressl":
  332. requiressl = parmValue;
  333. break;
  334. }
  335. }
  336. return addParm;
  337. }
  338. private SqlTransaction TransactionBegin () {
  339. // FIXME: need to keep track of
  340. // transaction in-progress
  341. trans = new SqlTransaction ();
  342. // using internal methods of SqlTransaction
  343. trans.SetConnection (this);
  344. trans.Begin();
  345. return trans;
  346. }
  347. private SqlTransaction TransactionBegin (IsolationLevel il) {
  348. // FIXME: need to keep track of
  349. // transaction in-progress
  350. TransactionBegin();
  351. trans.SetIsolationLevel (il);
  352. return trans;
  353. }
  354. #endregion
  355. #region Public Properties
  356. [MonoTODO]
  357. public ConnectionState State {
  358. get {
  359. return conState;
  360. }
  361. }
  362. public string ConnectionString {
  363. get {
  364. return connectionString;
  365. }
  366. set {
  367. SetConnectionString (value);
  368. }
  369. }
  370. public int ConnectionTimeout {
  371. get {
  372. return connectionTimeout;
  373. }
  374. }
  375. public string Database {
  376. get {
  377. return dbname;
  378. }
  379. }
  380. public string DataSource {
  381. get {
  382. return host;
  383. }
  384. }
  385. /*
  386. * FIXME: this is here because of Component?
  387. [MonoTODO]
  388. protected bool DesignMode {
  389. get {
  390. throw new NotImplementedException ();
  391. }
  392. }
  393. */
  394. public int PacketSize {
  395. get {
  396. throw new NotImplementedException ();
  397. }
  398. }
  399. public string ServerVersion {
  400. get {
  401. throw new NotImplementedException ();
  402. }
  403. }
  404. #region Internal Properties
  405. internal SqlTransaction Transaction {
  406. get {
  407. return trans;
  408. }
  409. }
  410. // this is for System.Data.SqlClient classes
  411. // to get the Postgres connection
  412. internal IntPtr PostgresConnection {
  413. get {
  414. return pgConn;
  415. }
  416. }
  417. internal ArrayList Types {
  418. get {
  419. return types.List;
  420. }
  421. }
  422. #endregion // Internal Properties
  423. #endregion
  424. #region Events and Delegates
  425. // FIXME: the two events belong here
  426. // however, i do not know about the delegates
  427. // also, they are stubs for now
  428. /*
  429. public delegate void
  430. SqlInfoMessageEventHandler (object sender,
  431. SqlInfoMessageEventArgs e);
  432. public event
  433. SqlInfoMessageEventHandler InfoMessage;
  434. public event
  435. StateChangeEventHandler StateChange;
  436. */
  437. #endregion
  438. #region Classes
  439. private class PostgresTypes {
  440. // TODO: create hashtable for
  441. // PostgreSQL types to .NET types
  442. // containing: oid, typname, SqlDbType
  443. private Hashtable hashTypes;
  444. private ArrayList pgTypes;
  445. private SqlConnection con;
  446. // Got this SQL with the permission from
  447. // the authors of libgda
  448. private const string SEL_SQL_GetTypes =
  449. "SELECT oid, typname FROM pg_type " +
  450. "WHERE typrelid = 0 AND typname !~ '^_' " +
  451. " AND typname not in ('SET', 'cid', " +
  452. "'int2vector', 'oidvector', 'regproc', " +
  453. "'smgr', 'tid', 'unknown', 'xid') " +
  454. "ORDER BY typname";
  455. internal PostgresTypes(SqlConnection sqlcon) {
  456. con = sqlcon;
  457. hashTypes = new Hashtable();
  458. }
  459. private void BuildTypes(IntPtr pgResult,
  460. int nRows, int nFields) {
  461. String value;
  462. int r, c;
  463. for(r = 0; r < nRows; r++) {
  464. PostgresType pgType =
  465. new PostgresType();
  466. for(c = 0; c < nFields; c++) {
  467. // get data value
  468. value = PostgresLibrary.
  469. PQgetvalue(
  470. pgResult,
  471. r, c);
  472. if(c == 0) {
  473. pgType.oid = Int32.Parse(value);
  474. }
  475. else if(c == 1) {
  476. pgType.typname = String.Copy(value);
  477. pgType.dbType = PostgresHelper.
  478. TypnameToSqlDbType(
  479. pgType.typname);
  480. pgTypes.Add(pgType);
  481. }
  482. // FIXME: needs to be Read Only
  483. // pgTypes = ArrayList.ReadOnly(pgTypes);
  484. }
  485. }
  486. }
  487. internal void Load() {
  488. pgTypes = new ArrayList();
  489. IntPtr pgResult; // PGresult
  490. ExecStatusType execStatus;
  491. if(con.State != ConnectionState.Open)
  492. throw new InvalidOperationException(
  493. "ConnnectionState is not Open");
  494. // FIXME: PQexec blocks
  495. // while PQsendQuery is non-blocking
  496. // which is better to use?
  497. // int PQsendQuery(PGconn *conn,
  498. // const char *query);
  499. // execute SQL command
  500. // uses internal property to get the PGConn IntPtr
  501. pgResult = PostgresLibrary.
  502. PQexec (con.PostgresConnection, SEL_SQL_GetTypes);
  503. execStatus = PostgresLibrary.
  504. PQresultStatus (pgResult);
  505. if(execStatus == ExecStatusType.PGRES_TUPLES_OK) {
  506. int nRows;
  507. int nFields;
  508. nRows = PostgresLibrary.
  509. PQntuples(pgResult);
  510. nFields = PostgresLibrary.
  511. PQnfields(pgResult);
  512. BuildTypes (pgResult, nRows, nFields);
  513. // close result set
  514. PostgresLibrary.PQclear (pgResult);
  515. }
  516. else {
  517. String errorMessage;
  518. errorMessage = PostgresLibrary.
  519. PQresStatus(execStatus);
  520. errorMessage += " " + PostgresLibrary.
  521. PQresultErrorMessage(pgResult);
  522. throw new SqlException(0, 0,
  523. errorMessage, 0, "",
  524. con.DataSource, "SqlConnection", 0);
  525. }
  526. }
  527. public ArrayList List {
  528. get {
  529. return pgTypes;
  530. }
  531. }
  532. }
  533. #endregion
  534. }
  535. }