File: VirtuosoCommand.cs

package info (click to toggle)
virtuoso-opensource 7.2.12%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 299,308 kB
  • sloc: ansic: 655,054; sql: 508,209; xml: 269,573; java: 84,064; javascript: 79,847; cpp: 37,662; sh: 32,429; cs: 25,702; php: 12,690; yacc: 11,666; lex: 7,933; makefile: 7,308; jsp: 4,523; awk: 1,719; perl: 1,013; ruby: 1,003; python: 326
file content (785 lines) | stat: -rw-r--r-- 19,204 bytes parent folder | download
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
//  
//  This file is part of the OpenLink Software Virtuoso Open-Source (VOS)
//  project.
//  
//  Copyright (C) 1998-2024 OpenLink Software
//  
//  This project is free software; you can redistribute it and/or modify it
//  under the terms of the GNU General Public License as published by the
//  Free Software Foundation; only version 2 of the License, dated June 1991.
//  
//  This program is distributed in the hope that it will be useful, but
//  WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//  General Public License for more details.
//  
//  You should have received a copy of the GNU General Public License along
//  with this program; if not, write to the Free Software Foundation, Inc.,
//  51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//  
//  
//
// $Id$
//

using System;
using System.Data;
using System.Data.Common;

using System.Diagnostics;
using System.Text;
#if (!MONO || ADONET2) // for now Mono doesn't have an IDE
using System.ComponentModel;
using System.Drawing;
#endif
using System.Text.RegularExpressions;

#if ODBC_CLIENT
namespace OpenLink.Data.VirtuosoOdbcClient
#elif CLIENT
namespace OpenLink.Data.VirtuosoClient
#else
namespace OpenLink.Data.Virtuoso
#endif
{
#if (!MONO || ADONET2) // for now Mono doesn't have an IDE
    [ToolboxBitmap(typeof(VirtuosoCommand), "OpenLink.Data.VirtuosoClient.VirtuosoCommand.bmp") ]
    [ToolboxItem(true)]
    [DesignTimeVisible(true)]
#endif
    public sealed class VirtuosoCommand : 
#if ADONET2
    DbCommand, ICloneable
#else
    System.ComponentModel.Component, ICloneable, IDbCommand
#endif
	{
		private VirtuosoConnection connection;
		private VirtuosoTransaction transaction;
		private string commandText;
		private CommandType commandType = CommandType.Text;
		private UpdateRowSource updatedRowSource = UpdateRowSource.None;
		private VirtuosoParameterCollection parameters;
		private int timeout = 30;
		private CommandConcurrency concurrency = CommandConcurrency.CONCUR_DEFAULT;
		private bool isPrepared = false;
		private bool isExecuted = false;
		private bool isFetching = false;
		private bool isExecuting = false;
		private bool isCanceling = false;
		private WeakReference dataReaderWeakRef = null;
		private IInnerCommand innerCommand;
		internal bool executeSecondaryStmt = false;
                internal string secondaryStmt = null;

		public VirtuosoCommand ()
			: this ("")
		{
		}

		public VirtuosoCommand (string cmdText)
			: this (cmdText, null)
		{
		}

		public VirtuosoCommand (string cmdText, VirtuosoConnection connection)
			: this (cmdText, connection, null)
		{
		}

		public VirtuosoCommand (string cmdText, VirtuosoConnection connection, VirtuosoTransaction transaction)
		{
			Debug.WriteLineIf (CLI.FnTrace.Enabled, "VirtuosoCommand.ctor()");
			this.commandText = cmdText;
			this.connection = connection;
			this.transaction = transaction;
			this.parameters = new VirtuosoParameterCollection (this);
		}

		/*
		 * Now inherited from the System.ComponentModel.Component 
		 * 
		~VirtuosoCommand ()
		{
			Dispose (false);
		}
		*/

		/*
		 * Now inherited from the System.ComponentModel.Component 
		 * 
		public void Dispose ()
		{
			Dispose (true);
			GC.SuppressFinalize (this);
		}
		*/

		public CommandConcurrency Concurrency
		{
			get
			{
				return concurrency;
			}
			set
			{
				concurrency = value;
			}
		}

#if ADONET2
		public override string CommandText
#else
		public string CommandText
#endif
		{
			get
			{
				Debug.WriteLineIf (CLI.FnTrace.Enabled, "VirtuosoCommand.get_CommandText()");
				return commandText;
			}
			set
			{
				Debug.WriteLineIf (CLI.FnTrace.Enabled, "VirtuosoCommand.set_CommandText()");
				if (commandText != value)
				{
					CheckState ();
					//DisposeStatement ();
					isPrepared = false;
					commandText = value;
				}
			}
		}

#if ADONET2
		public override int CommandTimeout
#else
		public int CommandTimeout
#endif
		{
			get
			{
				return timeout;
			}
			set
			{
				Debug.WriteLineIf (CLI.FnTrace.Enabled, "VirtuosoCommand.set_CommandTimeout()");
				if (timeout < 0)
					throw new ArgumentException ("Negative timeout value is specified.");

				if (timeout != value)
				{
					CheckState ();
					timeout = value;
				}
			}
		}

#if ADONET2
		public override CommandType CommandType
#else
		public CommandType CommandType
#endif
		{
			get
			{
				return commandType;
			}
			set
			{
				Debug.WriteLineIf (CLI.FnTrace.Enabled, "VirtuosoCommand.set_CommandType()");
				switch (value)
				{
					case CommandType.StoredProcedure:
					case CommandType.TableDirect:
					case CommandType.Text:
						break;
					default:
						throw new ArgumentException ("Invalid CommandType value.");
				}

				if (commandType != value)
				{
					CheckState ();
					//DisposeStatement ();
					isPrepared = false;
					commandType = value;
				}
			}
		}

#if ADONET2
		public new VirtuosoConnection Connection
#else
		public VirtuosoConnection Connection
#endif
		{
			/*
			 * The user should be able to set or change the connection at 
			 * any time.
			 */
			get
			{
				return connection;
			}
			set
			{
				/*
				 * The connection is associated with the transaction
				 * so set the transaction object to return a null reference if the connection 
				 * is reset.
				 */
				Debug.WriteLineIf (CLI.FnTrace.Enabled, "VirtuosoCommand.set_Connection()");
				if (connection != value)
				{
					CheckState ();
					DisposeStatement ();
					transaction = null;
					connection = (VirtuosoConnection) value;
				}
			}
		}
#if ADONET2
		protected override DbConnection DbConnection
		{
			get { return Connection; }
			set { Connection = (VirtuosoConnection) value; }
		}
#else
		IDbConnection IDbCommand.Connection
		{
			get { return Connection; }
			set { Connection = (VirtuosoConnection) value; }
		}
#endif


#if ADONET2
		public new VirtuosoParameterCollection Parameters
#else
		public VirtuosoParameterCollection Parameters
#endif
		{
			get { return parameters; }
		}

#if ADONET2
		protected override DbParameterCollection DbParameterCollection
		{
			get { return parameters; }
		}
#else
		IDataParameterCollection IDbCommand.Parameters
		{
			get { return parameters; }
		}
#endif

#if ADONET2
		public new VirtuosoTransaction Transaction
#else
		public VirtuosoTransaction Transaction
#endif
		{
			/*
			 * Set the transaction. Consider additional steps to ensure that the transaction
			 * is compatible with the connection, because the two are usually linked.
			 */
			get
			{
				return transaction;
			}
			set
			{
				Debug.WriteLineIf (CLI.FnTrace.Enabled, "VirtuosoCommand.set_Transaction()");
				if (transaction != value)
				{
					CheckState ();
					transaction = (VirtuosoTransaction) value;
				}
			}
		}

#if ADONET2
		protected override DbTransaction DbTransaction
		{
			get { return Transaction; }
			set { Transaction = (VirtuosoTransaction) value; }
		}
#else
		IDbTransaction IDbCommand.Transaction
		{
			get { return Transaction; }
			set { Transaction = (VirtuosoTransaction) value; }
		}
#endif

#if ADONET2
		public override UpdateRowSource UpdatedRowSource
#else
		public UpdateRowSource UpdatedRowSource
#endif
		{
			get { return updatedRowSource;  }
			set { updatedRowSource = value; }
		}

#if ADONET2
		public override void Cancel ()
#else
		public void Cancel ()
#endif
		{
			Debug.WriteLineIf (CLI.FnTrace.Enabled, "VirtuosoCommand.Cancel()");

			// There must be a valid and open connection.
			if (connection == null || connection.State != ConnectionState.Open)
				throw new InvalidOperationException ("Connection must be valid and open");

			if (innerCommand != null && (isExecuting || isExecuted))
			{
				isCanceling = true;
				innerCommand.Cancel ();
				isExecuted = false;
				isFetching = false;
				// TODO: do something about datareader if the cancel closes a resultset.
			}
		}

		object ICloneable.Clone ()
		{
			VirtuosoCommand command = new VirtuosoCommand ();
			command.Connection = this.Connection;
			command.CommandText = this.CommandText;
			command.CommandType = this.CommandType;
			command.CommandTimeout = this.CommandTimeout;
#if (!MONO || ADONET2)
			command.DesignTimeVisible = this.DesignTimeVisible;
#endif
			command.Transaction = this.Transaction;
			command.UpdatedRowSource = this.UpdatedRowSource;
                        
		        command.executeSecondaryStmt = this.executeSecondaryStmt;
                        command.secondaryStmt = this.secondaryStmt;

			foreach (VirtuosoParameter p in this.Parameters)
				command.Parameters.Add (((ICloneable) p).Clone());
			return command;
		}

#if ADONET2
		protected override DbParameter CreateDbParameter ()
		{
			return CreateParameter ();
		}
#else
		IDbDataParameter IDbCommand.CreateParameter ()
		{
			return CreateParameter ();
		}
#endif

#if ADONET2
        public new VirtuosoParameter CreateParameter()
#else
        public VirtuosoParameter CreateParameter()
#endif
        {
			Debug.WriteLineIf (CLI.FnTrace.Enabled, "VirtuosoCommand.CreateParameter()");
			return new VirtuosoParameter ();
		}

#if ADONET2
		public override int ExecuteNonQuery ()
#else
		public int ExecuteNonQuery ()
#endif
		{
			/*
			 * ExecuteNonQuery is intended for commands that do
			 * not return results, instead returning only the number
			 * of records affected.
			 */
			Debug.WriteLineIf (CLI.FnTrace.Enabled, "VirtuosoCommand.ExecuteNonQuery()");

			int records = 0;
			IDataReader reader = null;
			try
			{
				reader = ExecuteReader (CommandBehavior.Default);
				reader.Close ();
				records = reader.RecordsAffected;
			}
			finally
			{
				if (reader != null)
					reader.Close ();
			}

			return records;
		}

#if !ADONET2
		IDataReader IDbCommand.ExecuteReader ()
		{
			return ExecuteReader ();
		}
#endif

#if ADONET2
		public new VirtuosoDataReader ExecuteReader ()
#else
		public VirtuosoDataReader ExecuteReader ()
#endif
		{
			return ExecuteReader (CommandBehavior.Default);
		}

#if ADONET2
		protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
#else
		IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
#endif
		{
			return ExecuteReader (behavior);
		}

#if ADONET2
        public new VirtuosoDataReader ExecuteReader (CommandBehavior behavior)
#else
        public VirtuosoDataReader ExecuteReader (CommandBehavior behavior)
#endif
		{
			/*
			 * ExecuteReader should retrieve results from the data source
			 * and return a DataReader that allows the user to process 
			 * the results.
			 */
			Debug.WriteLineIf (CLI.FnTrace.Enabled, "VirtuosoCommand.ExecuteReader()");

			// There must be a valid and open connection.
			if (connection == null || connection.State != ConnectionState.Open)
				throw new InvalidOperationException ("Connection must be valid and open");

			VirtuosoConnection.permission.Demand ();

			CheckState ();

			if (innerCommand == null)
				innerCommand = connection.innerConnection.CreateInnerCommand (this);
			innerCommand.SetTimeout (timeout);
			innerCommand.SetCommandBehavior (behavior);
			innerCommand.SetConcurrencyMode(concurrency);

			bool schemaOnly = SchemaOnlyDataReader (behavior);
			string text = GetCommandText ();
		        bool isSparql = text.TrimStart(null).StartsWith("sparql", StringComparison.OrdinalIgnoreCase);
			if (schemaOnly)
			{
				if (!isPrepared)
				{
                    			if (!isSparql)
						text = replaceNamedParams (text);
					innerCommand.Prepare (text);
				}
			}
			else
			{
				if (!isSparql && parameters != null && parameters.Count > 0)
				{
					VirtuosoParameterCollection _parameters = handleNamedParams (text, parameters);
					Debug.Assert (_parameters.Count == parameters.Count, "Count mismatch in reordered parameter array");
					text = replaceNamedParams(text);
				}
				innerCommand.SetParameters (parameters);
				if (!isPrepared)
				{
					try
					{
						isExecuting = true;
						innerCommand.Execute (text);
                                                if (executeSecondaryStmt)
                                                  {
                                                    innerCommand.CloseCursor(false);
						    innerCommand.Execute (secondaryStmt);
                                                  }
					}
					finally
					{
						isExecuting = false;
					}
				}
				else
				{
					try
					{
						isExecuting = true;
						innerCommand.Execute ();
                                                if (executeSecondaryStmt)
                                                  {
                                                    innerCommand.CloseCursor(false);
						    innerCommand.Execute (secondaryStmt);
                                                  }
					}
					finally
					{
						isExecuting = false;
					}
				}
				isExecuted = true;
			}

			VirtuosoDataReader reader = new VirtuosoDataReader (connection, innerCommand, this, behavior, schemaOnly);
			dataReaderWeakRef = new WeakReference (reader);
			isFetching = true;
			return reader;
		}

#if ADONET2
        public override object ExecuteScalar ()
#else
		public object ExecuteScalar ()
#endif
		{
			/*
			 * ExecuteScalar assumes that the command will return a single
			 * row with a single column, or if more rows/columns are returned
			 * it will return the first column of the first row.
			 */
			Debug.WriteLineIf (CLI.FnTrace.Enabled, "VirtuosoCommand.ExecuteScalar()");

			object value = null;
			IDataReader reader = null;
			try
			{
				reader = ExecuteReader (CommandBehavior.Default);
				if (reader.Read () && reader.FieldCount > 0)
					value = reader.GetValue (0);
			}
			finally
			{
				if (reader != null)
					reader.Dispose ();
			}

			return value;
		}

#if ADONET2
		public override void Prepare ()
#else
		public void Prepare ()
#endif
		{
			Debug.WriteLineIf (CLI.FnTrace.Enabled, "VirtuosoCommand.Prepare()");
		}

		protected override void Dispose (bool disposing)
		{
			try
			{
			if (disposing)
			{
				DisposeStatement ();
			}
			base.Dispose (disposing);
			if (connection != null && 
			    connection.innerConnection != null)
				connection.innerConnection.RemoveCommand (this);
			connection = null;
			transaction = null;
		}
			catch (Exception e)
			{
				Debug.WriteLineIf(CLI.FnTrace.Enabled,
					"VirtuosoCommand.Dispose caught exception: " + e.Message);
			}
		}

		internal void OnConnectionClose ()
		{
			if (isFetching)
				CloseDataReader ();
			DisposeStatement ();
			transaction = null;
		}

		internal void CheckState ()
		{
			if (isFetching)
				CloseFinalizedDataReader ();
			if (isFetching || isExecuting)
				throw new InvalidOperationException ("The command object is busy.");
		}

		internal void CloseDataReader ()
		{
			Debug.Assert (dataReaderWeakRef != null);
			VirtuosoDataReader reader = (VirtuosoDataReader) dataReaderWeakRef.Target;
                        if (!isCanceling)
                        {
				Debug.Assert (isFetching);
				CloseCursor (true, reader);
                        }

			dataReaderWeakRef = null;
			isFetching = false;
		}

		/// <summary>
		/// Cleans up after garbage collected data reader.
		/// Does nothing if the data reader is still alive.
		/// </summary>
		internal void CloseFinalizedDataReader ()
		{
			Debug.Assert (isFetching);
			Debug.Assert (dataReaderWeakRef != null);
			VirtuosoDataReader reader = (VirtuosoDataReader) dataReaderWeakRef.Target;
			if (reader == null)
			{
				CloseCursor (true, null);
				dataReaderWeakRef = null;
				isFetching = false;
			}
		}

		private void CloseCursor (bool keepResults, VirtuosoDataReader reader)
		{
			if (isExecuted)
            {
			  if (keepResults && commandType == CommandType.StoredProcedure && innerCommand != null)
				  innerCommand.GetParameters ();
            }
            if (innerCommand != null)
			  innerCommand.CloseCursor (isExecuted);

			isExecuted = false;
		}

		internal bool GetNextResult ()
		{
			return innerCommand.GetNextResult ();
		}

		private bool SchemaOnlyDataReader (CommandBehavior behavior)
		{
			return ((behavior & CommandBehavior.SchemaOnly) != 0 && commandType != CommandType.StoredProcedure);
		}

		private void DisposeStatement ()
		{
			if (innerCommand != null)
			{
				innerCommand.Dispose ();
				innerCommand = null;
			}
		}

		private string GetCommandText ()
		{
			if (commandType == CommandType.TableDirect)
			{
				return "select * from " + commandText;
			}

			if (commandType == CommandType.StoredProcedure)
			{
				string retval = "";
				StringBuilder arglist = new StringBuilder ("(");
				bool firstArg = true;
				foreach (VirtuosoParameter param in parameters)
				{
					if (param.Direction == ParameterDirection.ReturnValue)
					{
						retval = "? = ";
					}
					else if (firstArg)
					{
						firstArg = false;
						arglist.Append ("?");
					}
					else
					{
						arglist.Append (", ?");
					}
				}
				arglist.Append (")");
				return "{" + retval + "call " + commandText + arglist + "}";
			}

			return commandText;
		}
        
		private bool m_design_time_visible = false;

#if (!MONO || ADONET2)
                [Browsable(false)]
                [DefaultValue(true)]
                [DesignOnly(true)]

#if ADONET2
                public override bool DesignTimeVisible
#else
                public bool DesignTimeVisible
#endif
                {
                    get
                    {
                        return m_design_time_visible;
                    }
                    set
                    {
                        m_design_time_visible = value;
                        TypeDescriptor.Refresh(this);
                    }
                }
#endif

		// Replaces any '@<name>' named parameters in the SQL command 
		// with '?' placeholders.
		internal string replaceNamedParams (string sql) 
		{
			string paramPattern = @"@\w+";
			Regex paramRegEx = new Regex(paramPattern);
			return paramRegEx.Replace(sql, "?");
		}

		// Reorders the parameter collection so that the order of named
		// parameters in the collection matches their order in the SQL 
		// command.
		internal VirtuosoParameterCollection handleNamedParams (string sql, VirtuosoParameterCollection _parameters)
		{
			string paramPattern = @"@\w+";
			Regex paramRegEx =  new Regex(paramPattern);
			Match match = paramRegEx.Match(sql);

			// If statement doesn't contain any named parameters
			if (!match.Success)
				return _parameters;

			VirtuosoParameterCollection newParameters = new VirtuosoParameterCollection (this);

			while(match.Success)
			{ 
				string paramName = String.Copy(match.Value);

				if (_parameters.IndexOf (paramName) >= 0)
					newParameters.Add (_parameters[_parameters.IndexOf (paramName)]);
				else
				{
					// Seems param name saved in parameter 
					// collection may or may not have a 
					// leading @
					string paramNameWithoutPrefix = String.Copy(paramName.Substring(1));
					if (_parameters.IndexOf (paramNameWithoutPrefix) >= 0)
					newParameters.Add (_parameters[_parameters.IndexOf (paramNameWithoutPrefix)]);
				}

		 		match = match.NextMatch();
			}
   
			return newParameters;
		}

	}
}