SqlCommand.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. //
  2. // System.Data.SqlClient.SqlCommand.cs
  3. //
  4. // Author:
  5. // Rodrigo Moya ([email protected])
  6. // Daniel Morgan ([email protected])
  7. // Tim Coleman ([email protected])
  8. // Diego Caravana ([email protected])
  9. //
  10. // (C) Ximian, Inc 2002 http://www.ximian.com/
  11. // (C) Daniel Morgan, 2002
  12. // Copyright (C) Tim Coleman, 2002
  13. //
  14. using Mono.Data.Tds;
  15. using Mono.Data.Tds.Protocol;
  16. using System;
  17. using System.Collections;
  18. using System.Collections.Specialized;
  19. using System.ComponentModel;
  20. using System.Data;
  21. using System.Data.Common;
  22. using System.Runtime.InteropServices;
  23. using System.Text;
  24. using System.Xml;
  25. namespace System.Data.SqlClient {
  26. [DesignerAttribute ("Microsoft.VSDesigner.Data.VS.SqlCommandDesigner, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.ComponentModel.Design.IDesigner")]
  27. public sealed class SqlCommand : Component, IDbCommand, ICloneable
  28. {
  29. #region Fields
  30. bool disposed = false;
  31. int commandTimeout;
  32. bool designTimeVisible;
  33. string commandText;
  34. CommandType commandType;
  35. SqlConnection connection;
  36. SqlTransaction transaction;
  37. UpdateRowSource updatedRowSource;
  38. CommandBehavior behavior = CommandBehavior.Default;
  39. SqlParameterCollection parameters;
  40. string preparedStatement = null;
  41. #endregion // Fields
  42. #region Constructors
  43. public SqlCommand()
  44. : this (String.Empty, null, null)
  45. {
  46. }
  47. public SqlCommand (string commandText)
  48. : this (commandText, null, null)
  49. {
  50. commandText = commandText;
  51. }
  52. public SqlCommand (string commandText, SqlConnection connection)
  53. : this (commandText, connection, null)
  54. {
  55. Connection = connection;
  56. }
  57. public SqlCommand (string commandText, SqlConnection connection, SqlTransaction transaction)
  58. {
  59. this.commandText = commandText;
  60. this.connection = connection;
  61. this.transaction = transaction;
  62. this.commandType = CommandType.Text;
  63. this.updatedRowSource = UpdateRowSource.Both;
  64. this.designTimeVisible = false;
  65. this.commandTimeout = 30;
  66. parameters = new SqlParameterCollection (this);
  67. }
  68. #endregion // Constructors
  69. #region Properties
  70. internal CommandBehavior CommandBehavior {
  71. get { return behavior; }
  72. }
  73. [DataCategory ("Data")]
  74. [DataSysDescription ("Command text to execute.")]
  75. [DefaultValue ("")]
  76. [EditorAttribute ("Microsoft.VSDesigner.Data.SQL.Design.SqlCommandTextEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  77. [RefreshProperties (RefreshProperties.All)]
  78. public string CommandText {
  79. get { return commandText; }
  80. set {
  81. if (value != commandText && preparedStatement != null)
  82. Unprepare ();
  83. commandText = value;
  84. }
  85. }
  86. [DataSysDescription ("Time to wait for command to execute.")]
  87. [DefaultValue (30)]
  88. public int CommandTimeout {
  89. get { return commandTimeout; }
  90. set {
  91. if (commandTimeout < 0)
  92. throw new ArgumentException ("The property value assigned is less than 0.");
  93. commandTimeout = value;
  94. }
  95. }
  96. [DataCategory ("Data")]
  97. [DataSysDescription ("How to interpret the CommandText.")]
  98. [DefaultValue (CommandType.Text)]
  99. [RefreshProperties (RefreshProperties.All)]
  100. public CommandType CommandType {
  101. get { return commandType; }
  102. set {
  103. if (value == CommandType.TableDirect)
  104. throw new ArgumentException ("CommandType.TableDirect is not supported by the Mono SqlClient Data Provider.");
  105. commandType = value;
  106. }
  107. }
  108. [DataCategory ("Behavior")]
  109. [DefaultValue (null)]
  110. [DataSysDescription ("Connection used by the command.")]
  111. [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )] public SqlConnection Connection {
  112. get { return connection; }
  113. set {
  114. if (transaction != null && connection.Transaction != null && connection.Transaction.IsOpen)
  115. throw new InvalidOperationException ("The Connection property was changed while a transaction was in progress.");
  116. transaction = null;
  117. connection = value;
  118. }
  119. }
  120. [Browsable (false)]
  121. [DefaultValue (true)]
  122. [DesignOnly (true)]
  123. public bool DesignTimeVisible {
  124. get { return designTimeVisible; }
  125. set { designTimeVisible = value; }
  126. }
  127. [DataCategory ("Data")]
  128. [DataSysDescription ("The parameters collection.")]
  129. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  130. public SqlParameterCollection Parameters {
  131. get { return parameters; }
  132. }
  133. internal ITds Tds {
  134. get { return Connection.Tds; }
  135. }
  136. IDbConnection IDbCommand.Connection {
  137. get { return Connection; }
  138. set {
  139. if (!(value is SqlConnection))
  140. throw new InvalidCastException ("The value was not a valid SqlConnection.");
  141. Connection = (SqlConnection) value;
  142. }
  143. }
  144. IDataParameterCollection IDbCommand.Parameters {
  145. get { return Parameters; }
  146. }
  147. IDbTransaction IDbCommand.Transaction {
  148. get { return Transaction; }
  149. set {
  150. if (!(value is SqlTransaction))
  151. throw new ArgumentException ();
  152. Transaction = (SqlTransaction) value;
  153. }
  154. }
  155. [Browsable (false)]
  156. [DataSysDescription ("The transaction used by the command.")]
  157. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  158. public SqlTransaction Transaction {
  159. get { return transaction; }
  160. set { transaction = value; }
  161. }
  162. [DataCategory ("Behavior")]
  163. [DataSysDescription ("When used by a DataAdapter.Update, how command results are applied to the current DataRow.")]
  164. [DefaultValue (UpdateRowSource.Both)]
  165. public UpdateRowSource UpdatedRowSource {
  166. get { return updatedRowSource; }
  167. set { updatedRowSource = value; }
  168. }
  169. #endregion // Fields
  170. #region Methods
  171. public void Cancel ()
  172. {
  173. if (Connection == null || Connection.Tds == null)
  174. return;
  175. Connection.Tds.Cancel ();
  176. }
  177. internal void CloseDataReader (bool moreResults)
  178. {
  179. Connection.DataReader = null;
  180. if ((behavior & CommandBehavior.CloseConnection) != 0)
  181. Connection.Close ();
  182. }
  183. public SqlParameter CreateParameter ()
  184. {
  185. return new SqlParameter ();
  186. }
  187. internal void DeriveParameters ()
  188. {
  189. if (commandType != CommandType.StoredProcedure)
  190. throw new InvalidOperationException (String.Format ("SqlCommand DeriveParameters only supports CommandType.StoredProcedure, not CommandType.{0}", commandType));
  191. ValidateCommand ("DeriveParameters");
  192. SqlParameterCollection localParameters = new SqlParameterCollection (this);
  193. localParameters.Add ("@P1", SqlDbType.NVarChar, commandText.Length).Value = commandText;
  194. string sql = "sp_procedure_params_rowset";
  195. Connection.Tds.ExecProc (sql, localParameters.MetaParameters, 0, true);
  196. SqlDataReader reader = new SqlDataReader (this);
  197. parameters.Clear ();
  198. object[] dbValues = new object[reader.FieldCount];
  199. while (reader.Read ()) {
  200. reader.GetValues (dbValues);
  201. parameters.Add (new SqlParameter (dbValues));
  202. }
  203. reader.Close ();
  204. }
  205. private void Execute (CommandBehavior behavior, bool wantResults)
  206. {
  207. TdsMetaParameterCollection parms = Parameters.MetaParameters;
  208. if (preparedStatement == null) {
  209. bool schemaOnly = ((CommandBehavior & CommandBehavior.SchemaOnly) > 0);
  210. bool keyInfo = ((CommandBehavior & CommandBehavior.SchemaOnly) > 0);
  211. StringBuilder sql1 = new StringBuilder ();
  212. StringBuilder sql2 = new StringBuilder ();
  213. if (schemaOnly || keyInfo)
  214. sql1.Append ("SET FMTONLY OFF;");
  215. if (keyInfo) {
  216. sql1.Append ("SET NO_BROWSETABLE ON;");
  217. sql2.Append ("SET NO_BROWSETABLE OFF;");
  218. }
  219. if (schemaOnly) {
  220. sql1.Append ("SET FMTONLY ON;");
  221. sql2.Append ("SET FMTONLY OFF;");
  222. }
  223. switch (CommandType) {
  224. case CommandType.StoredProcedure:
  225. if (keyInfo || schemaOnly)
  226. Connection.Tds.Execute (sql1.ToString ());
  227. Connection.Tds.ExecProc (CommandText, parms, CommandTimeout, wantResults);
  228. if (keyInfo || schemaOnly)
  229. Connection.Tds.Execute (sql2.ToString ());
  230. break;
  231. case CommandType.Text:
  232. string sql = String.Format ("{0}{1}{2}", sql1.ToString (), CommandText, sql2.ToString ());
  233. Connection.Tds.Execute (sql, parms, CommandTimeout, wantResults);
  234. break;
  235. }
  236. }
  237. else
  238. Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
  239. }
  240. public int ExecuteNonQuery ()
  241. {
  242. ValidateCommand ("ExecuteNonQuery");
  243. int result = 0;
  244. try {
  245. Execute (CommandBehavior.Default, false);
  246. result = Connection.Tds.RecordsAffected;
  247. }
  248. catch (TdsTimeoutException e) {
  249. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  250. }
  251. GetOutputParameters ();
  252. return result;
  253. }
  254. public SqlDataReader ExecuteReader ()
  255. {
  256. return ExecuteReader (CommandBehavior.Default);
  257. }
  258. public SqlDataReader ExecuteReader (CommandBehavior behavior)
  259. {
  260. ValidateCommand ("ExecuteReader");
  261. try {
  262. Execute (behavior, true);
  263. }
  264. catch (TdsTimeoutException e) {
  265. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  266. }
  267. Connection.DataReader = new SqlDataReader (this);
  268. return Connection.DataReader;
  269. }
  270. public object ExecuteScalar ()
  271. {
  272. ValidateCommand ("ExecuteScalar");
  273. try {
  274. Execute (CommandBehavior.Default, true);
  275. }
  276. catch (TdsTimeoutException e) {
  277. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  278. }
  279. if (!Connection.Tds.NextResult () || !Connection.Tds.NextRow ())
  280. return null;
  281. object result = Connection.Tds.ColumnValues [0];
  282. CloseDataReader (true);
  283. return result;
  284. }
  285. public XmlReader ExecuteXmlReader ()
  286. {
  287. ValidateCommand ("ExecuteXmlReader");
  288. try {
  289. Execute (CommandBehavior.Default, true);
  290. }
  291. catch (TdsTimeoutException e) {
  292. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  293. }
  294. SqlDataReader dataReader = new SqlDataReader (this);
  295. SqlXmlTextReader textReader = new SqlXmlTextReader (dataReader);
  296. XmlReader xmlReader = new XmlTextReader (textReader);
  297. return xmlReader;
  298. }
  299. internal void GetOutputParameters ()
  300. {
  301. IList list = Connection.Tds.OutputParameters;
  302. if (list != null && list.Count > 0) {
  303. int index = 0;
  304. foreach (SqlParameter parameter in parameters) {
  305. if (parameter.Direction != ParameterDirection.Input) {
  306. parameter.Value = list [index];
  307. index += 1;
  308. }
  309. if (index >= list.Count)
  310. break;
  311. }
  312. }
  313. }
  314. object ICloneable.Clone ()
  315. {
  316. return new SqlCommand (commandText, Connection);
  317. }
  318. IDbDataParameter IDbCommand.CreateParameter ()
  319. {
  320. return CreateParameter ();
  321. }
  322. IDataReader IDbCommand.ExecuteReader ()
  323. {
  324. return ExecuteReader ();
  325. }
  326. IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
  327. {
  328. return ExecuteReader (behavior);
  329. }
  330. public void Prepare ()
  331. {
  332. ValidateCommand ("Prepare");
  333. if (CommandType == CommandType.Text)
  334. preparedStatement = Connection.Tds.Prepare (CommandText, Parameters.MetaParameters);
  335. }
  336. public void ResetCommandTimeout ()
  337. {
  338. commandTimeout = 30;
  339. }
  340. private void Unprepare ()
  341. {
  342. Connection.Tds.Unprepare (preparedStatement);
  343. preparedStatement = null;
  344. }
  345. private void ValidateCommand (string method)
  346. {
  347. if (Connection == null)
  348. throw new InvalidOperationException (String.Format ("{0} requires a Connection object to continue.", method));
  349. if (Connection.Transaction != null && transaction != Connection.Transaction)
  350. throw new InvalidOperationException ("The Connection object does not have the same transaction as the command object.");
  351. if (Connection.State != ConnectionState.Open)
  352. throw new InvalidOperationException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
  353. if (commandText == String.Empty || commandText == null)
  354. throw new InvalidOperationException ("The command text for this Command has not been set.");
  355. if (Connection.DataReader != null)
  356. throw new InvalidOperationException ("There is already an open DataReader associated with this Connection which must be closed first.");
  357. if (Connection.XmlReader != null)
  358. throw new InvalidOperationException ("There is already an open XmlReader associated with this Connection which must be closed first.");
  359. }
  360. #endregion // Methods
  361. }
  362. }