2 // System.Data.SqlClient.SqlCommand.cs
5 // Rodrigo Moya (rodrigo@ximian.com)
6 // Daniel Morgan (danmorg@sc.rr.com)
7 // Tim Coleman (tim@timcoleman.com)
8 // Diego Caravana (diego@toth.it)
10 // (C) Ximian, Inc 2002 http://www.ximian.com/
11 // (C) Daniel Morgan, 2002
12 // Copyright (C) Tim Coleman, 2002
16 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
18 // Permission is hereby granted, free of charge, to any person obtaining
19 // a copy of this software and associated documentation files (the
20 // "Software"), to deal in the Software without restriction, including
21 // without limitation the rights to use, copy, modify, merge, publish,
22 // distribute, sublicense, and/or sell copies of the Software, and to
23 // permit persons to whom the Software is furnished to do so, subject to
24 // the following conditions:
26 // The above copyright notice and this permission notice shall be
27 // included in all copies or substantial portions of the Software.
29 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
30 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
31 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
32 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
33 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
34 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
35 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
39 using Mono.Data.Tds.Protocol;
42 using System.Collections;
43 using System.Collections.Specialized;
44 using System.ComponentModel;
46 using System.Data.Common;
48 using System.Data.Sql;
50 using System.Runtime.InteropServices;
54 namespace System.Data.SqlClient {
55 [DesignerAttribute ("Microsoft.VSDesigner.Data.VS.SqlCommandDesigner, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.ComponentModel.Design.IDesigner")]
56 [ToolboxItemAttribute ("System.Drawing.Design.ToolboxItem, "+ Consts.AssemblySystem_Drawing)]
58 [DefaultEventAttribute ("RecordsAffected")]
59 public sealed class SqlCommand : DbCommand, IDbCommand, ICloneable
61 public sealed class SqlCommand : Component, IDbCommand, ICloneable
66 const int DEFAULT_COMMAND_TIMEOUT = 30;
70 bool designTimeVisible;
72 CommandType commandType;
73 SqlConnection connection;
74 SqlTransaction transaction;
75 UpdateRowSource updatedRowSource;
76 CommandBehavior behavior = CommandBehavior.Default;
77 SqlParameterCollection parameters;
78 string preparedStatement;
80 SqlNotificationRequest notification;
81 bool notificationAutoEnlist;
89 : this (String.Empty, null, null)
93 public SqlCommand (string commandText)
94 : this (commandText, null, null)
98 public SqlCommand (string commandText, SqlConnection connection)
99 : this (commandText, connection, null)
103 public SqlCommand (string commandText, SqlConnection connection, SqlTransaction transaction)
105 this.commandText = commandText;
106 this.connection = connection;
107 this.transaction = transaction;
108 this.commandType = CommandType.Text;
109 this.updatedRowSource = UpdateRowSource.Both;
111 this.commandTimeout = DEFAULT_COMMAND_TIMEOUT;
113 notificationAutoEnlist = true;
115 designTimeVisible = true;
116 parameters = new SqlParameterCollection (this);
119 private SqlCommand(string commandText, SqlConnection connection, SqlTransaction transaction, CommandType commandType, UpdateRowSource updatedRowSource, bool designTimeVisible, int commandTimeout, SqlParameterCollection parameters)
121 this.commandText = commandText;
122 this.connection = connection;
123 this.transaction = transaction;
124 this.commandType = commandType;
125 this.updatedRowSource = updatedRowSource;
126 this.designTimeVisible = designTimeVisible;
127 this.commandTimeout = commandTimeout;
128 this.parameters = new SqlParameterCollection(this);
129 for (int i = 0;i < parameters.Count;i++)
130 this.parameters.Add(((ICloneable)parameters[i]).Clone());
132 #endregion // Constructors
136 internal CommandBehavior CommandBehavior {
137 get { return behavior; }
141 [DataSysDescription ("Command text to execute.")]
144 [EditorAttribute ("Microsoft.VSDesigner.Data.SQL.Design.SqlCommandTextEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
145 [RefreshProperties (RefreshProperties.All)]
152 if (commandText == null)
157 if (value != commandText && preparedStatement != null)
164 [DataSysDescription ("Time to wait for command to execute.")]
165 [DefaultValue (DEFAULT_COMMAND_TIMEOUT)]
172 get { return commandTimeout; }
175 throw new ArgumentException ("The property value assigned is less than 0.");
176 commandTimeout = value;
181 [DataSysDescription ("How to interpret the CommandText.")]
183 [DefaultValue (CommandType.Text)]
184 [RefreshProperties (RefreshProperties.All)]
189 CommandType CommandType {
190 get { return commandType; }
192 if (value == CommandType.TableDirect)
194 throw new ArgumentOutOfRangeException ("CommandType.TableDirect is not supported " +
195 "by the Mono SqlClient Data Provider.");
197 throw new ArgumentException ("CommandType.TableDirect is not supported by the Mono SqlClient Data Provider.");
200 ExceptionHelper.CheckEnumValue (typeof (CommandType), value);
205 [DefaultValue (null)]
207 [DataSysDescription ("Connection used by the command.")]
209 [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
214 SqlConnection Connection {
215 get { return connection; }
217 if (transaction != null && connection.Transaction != null && connection.Transaction.IsOpen)
218 throw new InvalidOperationException ("The Connection property was changed while a transaction was in progress.");
225 [DefaultValue (true)]
228 [EditorBrowsable (EditorBrowsableState.Never)]
234 bool DesignTimeVisible {
235 get { return designTimeVisible; }
236 set { designTimeVisible = value; }
240 [DataSysDescription ("The parameters collection.")]
242 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
247 SqlParameterCollection Parameters {
248 get { return parameters; }
252 get { return Connection.Tds; }
255 IDbConnection IDbCommand.Connection {
256 get { return Connection; }
258 if (!(value == null || value is SqlConnection))
259 throw new InvalidCastException ("The value was not a valid SqlConnection.");
260 Connection = (SqlConnection) value;
264 IDataParameterCollection IDbCommand.Parameters {
265 get { return Parameters; }
268 IDbTransaction IDbCommand.Transaction {
269 get { return Transaction; }
271 if (!(value == null || value is SqlTransaction))
272 throw new ArgumentException ();
273 Transaction = (SqlTransaction) value;
279 [DataSysDescription ("The transaction used by the command.")]
281 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
282 public new SqlTransaction Transaction {
283 get { return transaction; }
284 set { transaction = value; }
288 [DataSysDescription ("When used by a DataAdapter.Update, how command results are applied to the current DataRow.")]
290 [DefaultValue (UpdateRowSource.Both)]
295 UpdateRowSource UpdatedRowSource {
296 get { return updatedRowSource; }
298 ExceptionHelper.CheckEnumValue (typeof (UpdateRowSource), value);
299 updatedRowSource = value;
305 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
306 public SqlNotificationRequest Notification {
307 get { return notification; }
308 set { notification = value; }
311 [DefaultValue (true)]
312 public bool NotificationAutoEnlist {
313 get { return notificationAutoEnlist; }
314 set { notificationAutoEnlist = value; }
327 if (Connection == null || Connection.Tds == null)
329 Connection.Tds.Cancel ();
333 public SqlCommand Clone ()
335 return new SqlCommand (commandText, connection, transaction, commandType, updatedRowSource, designTimeVisible, commandTimeout, parameters);
339 internal void CloseDataReader (bool moreResults)
341 Connection.DataReader = null;
343 if ((behavior & CommandBehavior.CloseConnection) != 0)
346 // Reset the behavior
347 behavior = CommandBehavior.Default;
349 Tds.SequentialAccess = false;
352 public new SqlParameter CreateParameter ()
354 return new SqlParameter ();
357 internal void DeriveParameters ()
359 if (commandType != CommandType.StoredProcedure)
360 throw new InvalidOperationException (String.Format ("SqlCommand DeriveParameters only supports CommandType.StoredProcedure, not CommandType.{0}", commandType));
361 ValidateCommand ("DeriveParameters");
363 SqlParameterCollection localParameters = new SqlParameterCollection (this);
364 localParameters.Add ("@procedure_name", SqlDbType.NVarChar, CommandText.Length).Value = CommandText;
366 string sql = "sp_procedure_params_rowset";
369 Connection.Tds.ExecProc (sql, localParameters.MetaParameters, 0, true);
370 } catch (TdsInternalException ex) {
372 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
375 SqlDataReader reader = new SqlDataReader (this);
377 object[] dbValues = new object[reader.FieldCount];
379 while (reader.Read ()) {
380 reader.GetValues (dbValues);
381 parameters.Add (new SqlParameter (dbValues));
387 private void Execute (CommandBehavior behavior, bool wantResults)
390 Connection.Tds.RecordsAffected = -1;
391 TdsMetaParameterCollection parms = Parameters.MetaParameters;
392 foreach (TdsMetaParameter param in parms) {
393 param.Validate (index++);
396 if (preparedStatement == null) {
397 bool schemaOnly = ((behavior & CommandBehavior.SchemaOnly) > 0);
398 bool keyInfo = ((behavior & CommandBehavior.KeyInfo) > 0);
400 StringBuilder sql1 = new StringBuilder ();
401 StringBuilder sql2 = new StringBuilder ();
403 if (schemaOnly || keyInfo)
404 sql1.Append ("SET FMTONLY OFF;");
406 sql1.Append ("SET NO_BROWSETABLE ON;");
407 sql2.Append ("SET NO_BROWSETABLE OFF;");
410 sql1.Append ("SET FMTONLY ON;");
411 sql2.Append ("SET FMTONLY OFF;");
413 switch (CommandType) {
414 case CommandType.StoredProcedure:
416 if (keyInfo || schemaOnly)
417 Connection.Tds.Execute (sql1.ToString ());
418 Connection.Tds.ExecProc (CommandText, parms, CommandTimeout, wantResults);
419 if (keyInfo || schemaOnly)
420 Connection.Tds.Execute (sql2.ToString ());
421 } catch (TdsInternalException ex) {
423 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
426 case CommandType.Text:
428 if (sql2.Length > 0) {
429 sql = String.Format ("{0}{1};{2}", sql1.ToString (), CommandText, sql2.ToString ());
431 sql = String.Format ("{0}{1}", sql1.ToString (), CommandText);
434 Connection.Tds.Execute (sql, parms, CommandTimeout, wantResults);
435 } catch (TdsInternalException ex) {
437 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
444 Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
445 } catch (TdsInternalException ex) {
447 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
456 int ExecuteNonQuery ()
458 ValidateCommand ("ExecuteNonQuery");
460 behavior = CommandBehavior.Default;
463 Execute (CommandBehavior.Default, false);
464 result = Connection.Tds.RecordsAffected;
466 catch (TdsTimeoutException e) {
467 throw SqlException.FromTdsInternalException ((TdsInternalException) e);
470 GetOutputParameters ();
474 public new SqlDataReader ExecuteReader ()
476 return ExecuteReader (CommandBehavior.Default);
479 public new SqlDataReader ExecuteReader (CommandBehavior behavior)
481 ValidateCommand ("ExecuteReader");
483 this.behavior = behavior;
484 if ((behavior & CommandBehavior.SequentialAccess) != 0)
485 Tds.SequentialAccess = true;
486 Execute (behavior, true);
487 Connection.DataReader = new SqlDataReader (this);
488 } catch (TdsTimeoutException e) {
489 // if behavior is closeconnection, even if it throws exception
490 // the connection has to be closed.
491 if ((behavior & CommandBehavior.CloseConnection) != 0)
493 throw SqlException.FromTdsInternalException ((TdsInternalException) e);
494 } catch (SqlException) {
495 // if behavior is closeconnection, even if it throws exception
496 // the connection has to be closed.
497 if ((behavior & CommandBehavior.CloseConnection) != 0)
503 return Connection.DataReader;
510 object ExecuteScalar ()
513 object result = null;
514 ValidateCommand ("ExecuteScalar");
515 behavior = CommandBehavior.Default;
517 Execute (CommandBehavior.Default, true);
519 catch (TdsTimeoutException e) {
520 throw SqlException.FromTdsInternalException ((TdsInternalException) e);
524 if (Connection.Tds.NextResult () && Connection.Tds.NextRow ())
525 result = Connection.Tds.ColumnValues[0];
527 if (commandType == CommandType.StoredProcedure) {
528 Connection.Tds.SkipToEnd ();
529 GetOutputParameters ();
531 } catch (TdsInternalException ex) {
533 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
539 CloseDataReader (true);
543 public XmlReader ExecuteXmlReader ()
545 ValidateCommand ("ExecuteXmlReader");
546 behavior = CommandBehavior.Default;
548 Execute (CommandBehavior.Default, true);
549 } catch (TdsTimeoutException e) {
550 throw SqlException.FromTdsInternalException ((TdsInternalException) e);
553 SqlDataReader dataReader = new SqlDataReader (this);
554 SqlXmlTextReader textReader = new SqlXmlTextReader (dataReader);
555 XmlReader xmlReader = new XmlTextReader (textReader);
559 internal void GetOutputParameters ()
561 IList list = Connection.Tds.OutputParameters;
563 if (list != null && list.Count > 0) {
566 foreach (SqlParameter parameter in parameters) {
567 if (parameter.Direction != ParameterDirection.Input) {
568 parameter.Value = list [index];
571 if (index >= list.Count)
577 object ICloneable.Clone ()
579 return new SqlCommand (commandText, connection, transaction, commandType, updatedRowSource, designTimeVisible, commandTimeout, parameters);
584 IDbDataParameter IDbCommand.CreateParameter ()
586 return CreateParameter ();
589 IDataReader IDbCommand.ExecuteReader ()
591 return ExecuteReader ();
594 IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
596 return ExecuteReader (behavior);
601 protected override void Dispose (bool disposing)
603 if (disposed) return;
607 base.Dispose (disposing);
618 ValidateCommand ("Prepare");
620 if (CommandType == CommandType.StoredProcedure)
624 foreach (SqlParameter param in Parameters)
625 param.CheckIfInitialized ();
626 } catch (Exception e) {
627 throw new InvalidOperationException ("SqlCommand.Prepare requires " + e.Message);
630 preparedStatement = Connection.Tds.Prepare (CommandText, Parameters.MetaParameters);
633 public void ResetCommandTimeout ()
635 commandTimeout = DEFAULT_COMMAND_TIMEOUT;
638 private void Unprepare ()
640 Connection.Tds.Unprepare (preparedStatement);
641 preparedStatement = null;
644 private void ValidateCommand (string method)
646 if (Connection == null)
648 throw new NullReferenceException (String.Format ("{0} requires a Connection object to continue.", method));
650 throw new InvalidOperationException (String.Format ("{0} requires a Connection object to continue.", method));
652 if (Connection.Transaction != null && transaction != Connection.Transaction)
653 throw new InvalidOperationException ("The Connection object does not have the same transaction as the command object.");
654 if (Connection.State != ConnectionState.Open)
656 throw new NullReferenceException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
658 throw new InvalidOperationException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
660 if (CommandText.Length == 0)
661 throw new InvalidOperationException ("The command text for this Command has not been set.");
662 if (Connection.DataReader != null)
663 throw new InvalidOperationException ("There is already an open DataReader associated with this Connection which must be closed first.");
664 if (Connection.XmlReader != null)
665 throw new InvalidOperationException ("There is already an open XmlReader associated with this Connection which must be closed first.");
667 if (method.StartsWith ("Begin") && !Connection.AsyncProcessing)
668 throw new InvalidOperationException ("This Connection object is not " +
669 "in Asynchronous mode. Use 'Asynchronous" +
670 " Processing = true' to set it.");
675 protected override DbParameter CreateDbParameter ()
677 return CreateParameter ();
680 protected override DbDataReader ExecuteDbDataReader (CommandBehavior behavior)
682 return ExecuteReader (behavior);
685 protected override DbConnection DbConnection {
686 get { return Connection; }
687 set { Connection = (SqlConnection) value; }
690 protected override DbParameterCollection DbParameterCollection {
691 get { return Parameters; }
694 protected override DbTransaction DbTransaction {
695 get { return Transaction; }
696 set { Transaction = (SqlTransaction) value; }
700 #endregion // Methods
703 #region Asynchronous Methods
705 internal IAsyncResult BeginExecuteInternal (CommandBehavior behavior,
707 AsyncCallback callback,
710 IAsyncResult ar = null;
711 Connection.Tds.RecordsAffected = -1;
712 TdsMetaParameterCollection parms = Parameters.MetaParameters;
713 if (preparedStatement == null) {
714 bool schemaOnly = ((behavior & CommandBehavior.SchemaOnly) > 0);
715 bool keyInfo = ((behavior & CommandBehavior.KeyInfo) > 0);
717 StringBuilder sql1 = new StringBuilder ();
718 StringBuilder sql2 = new StringBuilder ();
720 if (schemaOnly || keyInfo)
721 sql1.Append ("SET FMTONLY OFF;");
723 sql1.Append ("SET NO_BROWSETABLE ON;");
724 sql2.Append ("SET NO_BROWSETABLE OFF;");
727 sql1.Append ("SET FMTONLY ON;");
728 sql2.Append ("SET FMTONLY OFF;");
731 switch (CommandType) {
732 case CommandType.StoredProcedure:
735 if (keyInfo || schemaOnly)
736 prolog = sql1.ToString ();
737 if (keyInfo || schemaOnly)
738 epilog = sql2.ToString ();
740 Connection.Tds.BeginExecuteProcedure (prolog,
747 } catch (TdsInternalException ex) {
749 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
752 case CommandType.Text:
753 string sql = String.Format ("{0}{1};{2}", sql1.ToString (), CommandText, sql2.ToString ());
756 ar = Connection.Tds.BeginExecuteQuery (sql, parms, callback, state);
758 ar = Connection.Tds.BeginExecuteNonQuery (sql, parms, callback, state);
759 } catch (TdsInternalException ex) {
761 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
768 Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
769 } catch (TdsInternalException ex) {
771 throw SqlException.FromTdsInternalException ((TdsInternalException) ex);
777 internal void EndExecuteInternal (IAsyncResult ar)
779 SqlAsyncResult sqlResult = ( (SqlAsyncResult) ar);
780 Connection.Tds.WaitFor (sqlResult.InternalResult);
781 Connection.Tds.CheckAndThrowException (sqlResult.InternalResult);
784 public IAsyncResult BeginExecuteNonQuery ()
786 return BeginExecuteNonQuery (null, null);
789 public IAsyncResult BeginExecuteNonQuery (AsyncCallback callback, object state)
791 ValidateCommand ("BeginExecuteNonQuery");
792 SqlAsyncResult ar = new SqlAsyncResult (callback, state);
793 ar.EndMethod = "EndExecuteNonQuery";
794 ar.InternalResult = BeginExecuteInternal (CommandBehavior.Default, false, ar.BubbleCallback, ar);
798 public int EndExecuteNonQuery (IAsyncResult ar)
800 ValidateAsyncResult (ar, "EndExecuteNonQuery");
801 EndExecuteInternal (ar);
803 int ret = Connection.Tds.RecordsAffected;
805 GetOutputParameters ();
806 ((SqlAsyncResult) ar).Ended = true;
810 public IAsyncResult BeginExecuteReader ()
812 return BeginExecuteReader (null, null, CommandBehavior.Default);
815 public IAsyncResult BeginExecuteReader (CommandBehavior behavior)
817 return BeginExecuteReader (null, null, behavior);
820 public IAsyncResult BeginExecuteReader (AsyncCallback callback, object state)
822 return BeginExecuteReader (callback, state, CommandBehavior.Default);
825 public IAsyncResult BeginExecuteReader (AsyncCallback callback, object state, CommandBehavior behavior)
827 ValidateCommand ("BeginExecuteReader");
828 this.behavior = behavior;
829 SqlAsyncResult ar = new SqlAsyncResult (callback, state);
830 ar.EndMethod = "EndExecuteReader";
831 IAsyncResult tdsResult = BeginExecuteInternal (behavior, true,
832 ar.BubbleCallback, state);
833 ar.InternalResult = tdsResult;
837 public SqlDataReader EndExecuteReader (IAsyncResult ar)
839 ValidateAsyncResult (ar, "EndExecuteReader");
840 EndExecuteInternal (ar);
841 SqlDataReader reader = null;
843 reader = new SqlDataReader (this);
844 } catch (TdsTimeoutException e) {
845 // if behavior is closeconnection, even if it throws exception
846 // the connection has to be closed.
847 if ((behavior & CommandBehavior.CloseConnection) != 0)
849 throw SqlException.FromTdsInternalException ((TdsInternalException) e);
850 } catch (SqlException) {
851 // if behavior is closeconnection, even if it throws exception
852 // the connection has to be closed.
853 if ((behavior & CommandBehavior.CloseConnection) != 0)
858 ((SqlAsyncResult) ar).Ended = true;
862 public IAsyncResult BeginExecuteXmlReader (AsyncCallback callback, object state)
864 ValidateCommand ("BeginExecuteXmlReader");
865 SqlAsyncResult ar = new SqlAsyncResult (callback, state);
866 ar.EndMethod = "EndExecuteXmlReader";
867 ar.InternalResult = BeginExecuteInternal (behavior, true,
868 ar.BubbleCallback, state);
872 public IAsyncResult BeginExecuteXmlReader ()
874 return BeginExecuteXmlReader (null, null);
878 public XmlReader EndExecuteXmlReader (IAsyncResult ar)
880 ValidateAsyncResult (ar, "EndExecuteXmlReader");
881 EndExecuteInternal (ar);
882 SqlDataReader reader = new SqlDataReader (this);
883 SqlXmlTextReader textReader = new SqlXmlTextReader (reader);
884 XmlReader xmlReader = new XmlTextReader (textReader);
885 ((SqlAsyncResult) ar).Ended = true;
889 internal void ValidateAsyncResult (IAsyncResult ar, string endMethod)
892 throw new ArgumentException ("result passed is null!");
893 if (! (ar is SqlAsyncResult))
894 throw new ArgumentException (String.Format ("cannot test validity of types {0}",
896 SqlAsyncResult result = (SqlAsyncResult) ar;
897 if (result.EndMethod != endMethod)
898 throw new InvalidOperationException (String.Format ("Mismatched {0} called for AsyncResult. " +
899 "Expected call to {1} but {0} is called instead.",
900 endMethod, result.EndMethod));
902 throw new InvalidOperationException (String.Format ("The method {0} cannot be called " +
903 "more than once for the same AsyncResult.", endMethod));
906 #endregion // Asynchronous Methods
908 public event StatementCompletedEventHandler StatementCompleted;