Welcome to mirror list, hosted at ThFree Co, Russian Federation.

SqlConnection.cs « System.Data.SqlClient « System.Data « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0bd37605cc64807d265d4d9fde9bbe7b3f7d31a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
//
// System.Data.SqlClient.SqlConnection.cs
//
// Author:
//   Rodrigo Moya (rodrigo@ximian.com)
//   Daniel Morgan (danmorg@sc.rr.com)
//
// (C) Ximian, Inc 2002
// (C) Daniel Morgan 2002
//
// Credits:
//    SQL and concepts were used from libgda 0.8.190 (GNOME Data Access)
//    http://www.gnome-db.org/
//    with permission from the authors of the
//    PostgreSQL provider in libgda:
//        Michael Lausch <michael@lausch.at>
//        Rodrigo Moya <rodrigo@gnome-db.org>
//        Vivien Malerba <malerba@gnome-db.org>
//        Gonzalo Paniagua Javier <gonzalo@gnome-db.org>
//

// use #define DEBUG_SqlConnection if you want to spew debug messages
// #define DEBUG_SqlConnection

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Runtime.InteropServices;
using System.Text;

namespace System.Data.SqlClient {

	/// <summary>
	/// Represents an open connection to a SQL data source
	/// </summary>
	public sealed class SqlConnection : Component, IDbConnection,
		ICloneable	
	{
		// FIXME: Need to implement class Component, 
		// and interfaces: ICloneable and IDisposable	

		#region Fields

		private PostgresTypes types = null;
		private IntPtr pgConn = IntPtr.Zero;    

		// PGConn (Postgres Connection)
		private string connectionString = "";    
		// OLE DB Connection String
		private string pgConnectionString = ""; 
		// PostgreSQL Connection String
		private SqlTransaction trans = null;
		private int connectionTimeout = 15;     
		// default for 15 seconds
		
		// connection parameters in connection string
		private string host = "";     
		// Name of host to connect to
		private string hostaddr = ""; 
		// IP address of host to connect to
		// should be in "n.n.n.n" format
		private string port = "";     
		// Port number to connect to at the server host
		private string dbname = "";   // The database name. 
		private string user = "";     // User name to connect as. 
		private string password = "";
		// Password to be used if the server 
		// demands password authentication.  		
		private string options = ""; 
		// Trace/debug options to be sent to the server. 
		private string tty = ""; 
		// A file or tty for optional 
		// debug output from the backend. 
		private string requiressl = "";
		// Set to 1 to require 
		// SSL connection to the backend. 
		// Libpq will then refuse to connect 
		// if the server does not 
		// support SSL. Set to 0 (default) to 
		// negotiate with server. 

		// connection state
		private ConnectionState conState = ConnectionState.Closed;
		
		// DataReader state
		private SqlDataReader rdr = null;
		private bool dataReaderOpen = false;
		// FIXME: if true, throw an exception if SqlConnection 
		//        is used for anything other than reading
		//        data using SqlDataReader
		
		private string versionString = "Unknown";

		private bool disposed = false;

		#endregion // Fields

		#region Constructors

		// A lot of the defaults were initialized in the Fields
		[MonoTODO]
		public SqlConnection () {

		}
	
		[MonoTODO]
		public SqlConnection (String connectionString) {
			SetConnectionString (connectionString);
		}

		#endregion // Constructors

		#region Destructors

		protected override void Dispose(bool disposing) {
			if(!this.disposed)
				try {
					if(disposing) {
						// release any managed resources
					}
					// release any unmanaged resources
					// close any handles
										
					this.disposed = true;
				}
				finally {
					base.Dispose(disposing);
				}
		}
	
		// aka Finalize()
		// [ClassInterface(ClassInterfaceType.AutoDual)]
		[MonoTODO]
		~SqlConnection() {
			Dispose (false);
		}
		
		#endregion // Destructors

		#region Public Methods

		IDbTransaction IDbConnection.BeginTransaction () {
			return BeginTransaction ();
		}

		public SqlTransaction BeginTransaction () {
			return TransactionBegin (); // call private method
		}

		IDbTransaction IDbConnection.BeginTransaction (IsolationLevel 
			il) {
			return BeginTransaction (il);
		}

		public SqlTransaction BeginTransaction (IsolationLevel il) {
			return TransactionBegin (il); // call private method
		}

		// PostgreSQL does not support named transactions/savepoint
		//            nor nested transactions
		[Obsolete]
		public SqlTransaction BeginTransaction(string transactionName) {
			return TransactionBegin (); // call private method
		}

		[Obsolete]
		public SqlTransaction BeginTransaction(IsolationLevel iso,
			string transactionName) {
			return TransactionBegin (iso); // call private method
		}

		[MonoTODO]
		public void ChangeDatabase (string databaseName) {
			throw new NotImplementedException ();
		}

		object ICloneable.Clone() {
			throw new NotImplementedException ();
		}
		
		[MonoTODO]
		public void Close () {
			if(dataReaderOpen == true) {
				// TODO: what do I do if
				// the user Closes the connection
				// without closing the Reader first?

			}			
			CloseDataSource ();
		}

		IDbCommand IDbConnection.CreateCommand () {
			return CreateCommand ();
		}

		public SqlCommand CreateCommand () {
			SqlCommand sqlcmd = new SqlCommand ("", this);

			return sqlcmd;
		}

		[MonoTODO]
		public void Open () {
			if(dbname.Equals(""))
				throw new InvalidOperationException(
					"dbname missing");
			else if(conState == ConnectionState.Open)
				throw new InvalidOperationException(
					"ConnnectionState is already Open");

			ConnStatusType connStatus;

			// FIXME: check to make sure we have 
			//        everything to connect,
			//        otherwise, throw an exception

			pgConn = PostgresLibrary.PQconnectdb 
				(pgConnectionString);

			// FIXME: should we use PQconnectStart/PQconnectPoll
			//        instead of PQconnectdb?  
			// PQconnectdb blocks 
			// PQconnectStart/PQconnectPoll is non-blocking
			
			connStatus = PostgresLibrary.PQstatus (pgConn);
			if(connStatus == ConnStatusType.CONNECTION_OK) {
				// Successfully Connected
				disposed = false;
				SetupConnection();
			}
			else {
				String errorMessage = PostgresLibrary.
					PQerrorMessage (pgConn);
				errorMessage += ": Could not connect to database.";

				throw new SqlException(0, 0,
					errorMessage, 0, "",
					host, "SqlConnection", 0);
			}
		}

		#endregion // Public Methods

		#region Internal Methods

		// Used to prevent SqlConnection
		// from doing anything while
		// SqlDataReader is open.
		// Open the Reader. (called from SqlCommand)
		internal void OpenReader(SqlDataReader reader) 
		{	
			if(dataReaderOpen == true) {
				// TODO: throw exception here?
				//       because a reader
				//       is already open
			}
			else {
				rdr = reader;
				dataReaderOpen = true;
			}
		}

		// Used to prevent SqlConnection
		// from doing anything while
		// SqlDataReader is open
		// Close the Reader (called from SqlCommand)
		// if closeConnection true, Close() the connection
		// this is based on CommandBehavior.CloseConnection
		internal void CloseReader(bool closeConnection)
		{	if(closeConnection == true)
				CloseDataSource();
			else
				dataReaderOpen = false;
		}

		#endregion // Internal Methods

		#region Private Methods

		private void SetupConnection() {
			
			conState = ConnectionState.Open;

			// FIXME: load types into hashtable
			types = new PostgresTypes(this);
			types.Load();

			versionString = GetDatabaseServerVersion();

			// set DATE style to YYYY/MM/DD
			IntPtr pgResult = IntPtr.Zero;
			pgResult = PostgresLibrary.PQexec (pgConn, "SET DATESTYLE TO 'ISO'");
			PostgresLibrary.PQclear (pgResult);
			pgResult = IntPtr.Zero;
		}

		private string GetDatabaseServerVersion() 
		{
			SqlCommand cmd = new SqlCommand("select version()",this);
			return (string) cmd.ExecuteScalar();
		}

		private void CloseDataSource () {
			// FIXME: just a quick hack
			if(conState == ConnectionState.Open) {
				if(trans != null)
					if(trans.DoingTransaction == true) {
						trans.Rollback();
						// trans.Dispose();
						trans = null;
					}

				conState = ConnectionState.Closed;
				PostgresLibrary.PQfinish (pgConn);
				pgConn = IntPtr.Zero;
			}
		}

		private void SetConnectionString (string connectionString) {
			// FIXME: perform error checking on string
			// while translating string from 
			// OLE DB format to PostgreSQL 
			// connection string format
			//
			//     OLE DB: "host=localhost;dbname=test;user=joe;password=smoe"
			// PostgreSQL: "host=localhost dbname=test user=joe password=smoe"
			//
			// For OLE DB, you would have the additional 
			// "provider=postgresql"
			// OleDbConnection you would be using libgda
			//
			// Also, parse the connection string into properties

			// FIXME: if connection is open, you can 
			//        not set the connection
			//        string, throw an exception

			this.connectionString = connectionString;
			pgConnectionString = ConvertStringToPostgres (
				connectionString);

#if DEBUG_SqlConnection
			Console.WriteLine(
				"OLE-DB Connection String    [in]: " +
				this.ConnectionString);
			Console.WriteLine(
				"Postgres Connection String [out]: " +
				pgConnectionString);
#endif // DEBUG_SqlConnection
		}

		private String ConvertStringToPostgres (String 
			oleDbConnectionString) {
			StringBuilder postgresConnection = 
				new StringBuilder();
			string result;
			string[] connectionParameters;

			char[] semicolon = new Char[1];
			semicolon[0] = ';';
			
			// FIXME: what is the max number of value pairs 
			//        can there be for the OLE DB 
			//	  connnection string? what about libgda max?
			//        what about postgres max?

			// FIXME: currently assuming value pairs are like:
			//        "key1=value1;key2=value2;key3=value3"
			//        Need to deal with values that have
			//        single or double quotes.  And error 
			//        handling of that too.
			//        "key1=value1;key2='value2';key=\"value3\""

			// FIXME: put the connection parameters 
			//        from the connection
			//        string into a 
			//        Hashtable (System.Collections)
			//        instead of using private variables 
			//        to store them
			connectionParameters = oleDbConnectionString.
				Split (semicolon);
			foreach (string sParameter in connectionParameters) {
				if(sParameter.Length > 0) {
					BreakConnectionParameter (sParameter);
					postgresConnection.
						Append (sParameter + 
						" ");
				}
			}
			result = postgresConnection.ToString ();
			return result;
		}

		private bool BreakConnectionParameter (String sParameter) {	
			bool addParm = true;
			int index;

			index = sParameter.IndexOf ("=");
			if (index > 0) {	
				string parmKey, parmValue;

				// separate string "key=value" to 
				// string "key" and "value"
				parmKey = sParameter.Substring (0, index);
				parmValue = sParameter.Substring (index + 1,
					sParameter.Length - index - 1);

				switch(parmKey.ToLower()) {
				case "hostaddr":
					hostaddr = parmValue;
					break;

				case "port":
					port = parmValue;
					break;

				case "host":
					// set DataSource property
					host = parmValue;
					break;

				case "dbname":
					// set Database property
					dbname = parmValue;
					break;

				case "user":
					user = parmValue;
					break;

				case "password":
					password = parmValue;
					//	addParm = false;
					break;

				case "options":
					options = parmValue;
					break;

				case "tty":
					tty = parmValue;
					break;
							
				case "requiressl":
					requiressl = parmValue;
					break;
				}
			}
			return addParm;
		}

		private SqlTransaction TransactionBegin () {
			// FIXME: need to keep track of 
			// transaction in-progress
			trans = new SqlTransaction ();
			// using internal methods of SqlTransaction
			trans.SetConnection (this);
			trans.Begin();

			return trans;
		}

		private SqlTransaction TransactionBegin (IsolationLevel il) {
			// FIXME: need to keep track of 
			// transaction in-progress
			TransactionBegin();
			trans.SetIsolationLevel (il);
			
			return trans;
		}

		#endregion

		#region Public Properties

		[MonoTODO]
		public ConnectionState State 		{
			get { 
				return conState;
			}
		}

		public string ConnectionString	{
			get { 
				return connectionString;
			}
			set { 
				SetConnectionString (value);
			}
		}
		
		public int ConnectionTimeout {
			get { 
				return connectionTimeout; 
			}
		}

		public string Database	{
			get { 
				return dbname; 
			}
		}

		public string DataSource {
			get {
				return host;
			}
		}

		public int PacketSize {
			get { 
				throw new NotImplementedException ();
			}
		}

		public string ServerVersion {
			get { 
				return versionString;
			}
		}

		#endregion // Public Properties

		#region Internal Properties

		// For System.Data.SqlClient classes
		// to get the current transaction
		// in progress - if any
		internal SqlTransaction Transaction {
			get {
				return trans;
			}
		}

		// For System.Data.SqlClient classes 
		// to get the unmanaged PostgreSQL connection
		internal IntPtr PostgresConnection {
			get {
				return pgConn;
			}
		}

		// For System.Data.SqlClient classes
		// to get the list PostgreSQL types
		// so can look up based on OID to
		// get the .NET System type.
		internal ArrayList Types {
			get {
				return types.List;
			}
		}

		// Used to prevent SqlConnection
		// from doing anything while
		// SqlDataReader is open
		internal bool IsReaderOpen {
			get {
				return dataReaderOpen;
			}
		}

		#endregion // Internal Properties

		#region Events
                
		public event 
		SqlInfoMessageEventHandler InfoMessage;

		public event 
		StateChangeEventHandler StateChange;
		
		#endregion

		#region Inner Classes

		private class PostgresTypes {
			// TODO: create hashtable for 
			// PostgreSQL types to .NET types
			// containing: oid, typname, SqlDbType

			private Hashtable hashTypes;
			private ArrayList pgTypes;
			private SqlConnection con;

			// Got this SQL with the permission from 
			// the authors of libgda
			private const string SEL_SQL_GetTypes = 
				"SELECT oid, typname FROM pg_type " +
				"WHERE typrelid = 0 AND typname !~ '^_' " +
				" AND  typname not in ('SET', 'cid', " +
				"'int2vector', 'oidvector', 'regproc', " +
				"'smgr', 'tid', 'unknown', 'xid') " +
				"ORDER BY typname";

			internal PostgresTypes(SqlConnection sqlcon) {
				
				con = sqlcon;
				hashTypes = new Hashtable();
			}

			private void AddPgType(Hashtable types, 
				string typname, DbType dbType) {

				PostgresType pgType = new PostgresType();
			
				pgType.typname = typname;
				pgType.dbType = dbType;	

				types.Add(pgType.typname, pgType);
			}

			private void BuildTypes(IntPtr pgResult, 
				int nRows, int nFields) {

				String value;

				int r;
				for(r = 0; r < nRows; r++) {
					PostgresType pgType = 
						new PostgresType();

					// get data value (oid)
					value = PostgresLibrary.
						PQgetvalue(
							pgResult,
							r, 0);
						
					pgType.oid = Int32.Parse(value);

					// get data value (typname)
					value = PostgresLibrary.
						PQgetvalue(
						pgResult,
						r, 1);	
					pgType.typname = String.Copy(value);
					pgType.dbType = PostgresHelper.
							TypnameToSqlDbType(
								pgType.typname);

					pgTypes.Add(pgType);
				}
				pgTypes = ArrayList.ReadOnly(pgTypes);
			}

			internal void Load() {
				pgTypes = new ArrayList();
				IntPtr pgResult = IntPtr.Zero; // PGresult
				
				if(con.State != ConnectionState.Open)
					throw new InvalidOperationException(
						"ConnnectionState is not Open");

				// FIXME: PQexec blocks 
				// while PQsendQuery is non-blocking
				// which is better to use?
				// int PQsendQuery(PGconn *conn,
				//        const char *query);

				// execute SQL command
				// uses internal property to get the PGConn IntPtr
				pgResult = PostgresLibrary.
					PQexec (con.PostgresConnection, SEL_SQL_GetTypes);

				if(pgResult.Equals(IntPtr.Zero)) {
					throw new SqlException(0, 0,
						"No Resultset from PostgreSQL", 0, "",
						con.DataSource, "SqlConnection", 0);
				}
				else {
					ExecStatusType execStatus;

					execStatus = PostgresLibrary.
						PQresultStatus (pgResult);
			
					if(execStatus == ExecStatusType.PGRES_TUPLES_OK) {
						int nRows;
						int nFields;

						nRows = PostgresLibrary.
							PQntuples(pgResult);

						nFields = PostgresLibrary.
							PQnfields(pgResult);

						BuildTypes (pgResult, nRows, nFields);

						// close result set
						PostgresLibrary.PQclear (pgResult);
						pgResult = IntPtr.Zero;
					}
					else {
						String errorMessage;
				
						errorMessage = PostgresLibrary.
							PQresStatus(execStatus);

						errorMessage += " " + PostgresLibrary.
							PQresultErrorMessage(pgResult);

						// close result set
						PostgresLibrary.PQclear (pgResult);
						pgResult = IntPtr.Zero;

						throw new SqlException(0, 0,
							errorMessage, 0, "",
							con.DataSource, "SqlConnection", 0);
					}
				}
			}

			public ArrayList List {
				get {
					return pgTypes;
				}
			}
		}

		#endregion
	}
}