SqlCommand.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. //
  15. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  16. //
  17. // Permission is hereby granted, free of charge, to any person obtaining
  18. // a copy of this software and associated documentation files (the
  19. // "Software"), to deal in the Software without restriction, including
  20. // without limitation the rights to use, copy, modify, merge, publish,
  21. // distribute, sublicense, and/or sell copies of the Software, and to
  22. // permit persons to whom the Software is furnished to do so, subject to
  23. // the following conditions:
  24. //
  25. // The above copyright notice and this permission notice shall be
  26. // included in all copies or substantial portions of the Software.
  27. //
  28. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  29. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  30. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  31. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  32. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  33. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  34. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  35. //
  36. using Mono.Data.Tds;
  37. using Mono.Data.Tds.Protocol;
  38. using System;
  39. using System.Collections;
  40. using System.Collections.Specialized;
  41. using System.ComponentModel;
  42. using System.Data;
  43. using System.Data.Common;
  44. using System.Runtime.InteropServices;
  45. using System.Text;
  46. using System.Xml;
  47. namespace System.Data.SqlClient {
  48. [DesignerAttribute ("Microsoft.VSDesigner.Data.VS.SqlCommandDesigner, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.ComponentModel.Design.IDesigner")]
  49. [ToolboxItemAttribute ("System.Drawing.Design.ToolboxItem, "+ Consts.AssemblySystem_Drawing)]
  50. public sealed class SqlCommand : Component, IDbCommand, ICloneable
  51. {
  52. #region Fields
  53. bool disposed = false;
  54. int commandTimeout;
  55. bool designTimeVisible;
  56. string commandText;
  57. CommandType commandType;
  58. SqlConnection connection;
  59. SqlTransaction transaction;
  60. UpdateRowSource updatedRowSource;
  61. CommandBehavior behavior = CommandBehavior.Default;
  62. SqlParameterCollection parameters;
  63. string preparedStatement = null;
  64. #endregion // Fields
  65. #region Constructors
  66. public SqlCommand()
  67. : this (String.Empty, null, null)
  68. {
  69. }
  70. public SqlCommand (string commandText)
  71. : this (commandText, null, null)
  72. {
  73. commandText = commandText;
  74. }
  75. public SqlCommand (string commandText, SqlConnection connection)
  76. : this (commandText, connection, null)
  77. {
  78. Connection = connection;
  79. }
  80. public SqlCommand (string commandText, SqlConnection connection, SqlTransaction transaction)
  81. {
  82. this.commandText = commandText;
  83. this.connection = connection;
  84. this.transaction = transaction;
  85. this.commandType = CommandType.Text;
  86. this.updatedRowSource = UpdateRowSource.Both;
  87. this.designTimeVisible = false;
  88. this.commandTimeout = 30;
  89. parameters = new SqlParameterCollection (this);
  90. }
  91. #endregion // Constructors
  92. #region Properties
  93. internal CommandBehavior CommandBehavior {
  94. get { return behavior; }
  95. }
  96. [DataCategory ("Data")]
  97. [DataSysDescription ("Command text to execute.")]
  98. [DefaultValue ("")]
  99. [EditorAttribute ("Microsoft.VSDesigner.Data.SQL.Design.SqlCommandTextEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  100. [RefreshProperties (RefreshProperties.All)]
  101. public string CommandText {
  102. get { return commandText; }
  103. set {
  104. if (value != commandText && preparedStatement != null)
  105. Unprepare ();
  106. commandText = value;
  107. }
  108. }
  109. [DataSysDescription ("Time to wait for command to execute.")]
  110. [DefaultValue (30)]
  111. public int CommandTimeout {
  112. get { return commandTimeout; }
  113. set {
  114. if (commandTimeout < 0)
  115. throw new ArgumentException ("The property value assigned is less than 0.");
  116. commandTimeout = value;
  117. }
  118. }
  119. [DataCategory ("Data")]
  120. [DataSysDescription ("How to interpret the CommandText.")]
  121. [DefaultValue (CommandType.Text)]
  122. [RefreshProperties (RefreshProperties.All)]
  123. public CommandType CommandType {
  124. get { return commandType; }
  125. set {
  126. if (value == CommandType.TableDirect)
  127. throw new ArgumentException ("CommandType.TableDirect is not supported by the Mono SqlClient Data Provider.");
  128. commandType = value;
  129. }
  130. }
  131. [DataCategory ("Behavior")]
  132. [DefaultValue (null)]
  133. [DataSysDescription ("Connection used by the command.")]
  134. [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )] public SqlConnection Connection {
  135. get { return connection; }
  136. set {
  137. if (transaction != null && connection.Transaction != null && connection.Transaction.IsOpen)
  138. throw new InvalidOperationException ("The Connection property was changed while a transaction was in progress.");
  139. transaction = null;
  140. connection = value;
  141. }
  142. }
  143. [Browsable (false)]
  144. [DefaultValue (true)]
  145. [DesignOnly (true)]
  146. public bool DesignTimeVisible {
  147. get { return designTimeVisible; }
  148. set { designTimeVisible = value; }
  149. }
  150. [DataCategory ("Data")]
  151. [DataSysDescription ("The parameters collection.")]
  152. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  153. public SqlParameterCollection Parameters {
  154. get { return parameters; }
  155. }
  156. internal ITds Tds {
  157. get { return Connection.Tds; }
  158. }
  159. IDbConnection IDbCommand.Connection {
  160. get { return Connection; }
  161. set {
  162. if (!(value is SqlConnection))
  163. throw new InvalidCastException ("The value was not a valid SqlConnection.");
  164. Connection = (SqlConnection) value;
  165. }
  166. }
  167. IDataParameterCollection IDbCommand.Parameters {
  168. get { return Parameters; }
  169. }
  170. IDbTransaction IDbCommand.Transaction {
  171. get { return Transaction; }
  172. set {
  173. if (!(value is SqlTransaction))
  174. throw new ArgumentException ();
  175. Transaction = (SqlTransaction) value;
  176. }
  177. }
  178. [Browsable (false)]
  179. [DataSysDescription ("The transaction used by the command.")]
  180. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  181. public SqlTransaction Transaction {
  182. get { return transaction; }
  183. set { transaction = value; }
  184. }
  185. [DataCategory ("Behavior")]
  186. [DataSysDescription ("When used by a DataAdapter.Update, how command results are applied to the current DataRow.")]
  187. [DefaultValue (UpdateRowSource.Both)]
  188. public UpdateRowSource UpdatedRowSource {
  189. get { return updatedRowSource; }
  190. set { updatedRowSource = value; }
  191. }
  192. #endregion // Fields
  193. #region Methods
  194. public void Cancel ()
  195. {
  196. if (Connection == null || Connection.Tds == null)
  197. return;
  198. Connection.Tds.Cancel ();
  199. }
  200. internal void CloseDataReader (bool moreResults)
  201. {
  202. Connection.DataReader = null;
  203. if ((behavior & CommandBehavior.CloseConnection) != 0)
  204. Connection.Close ();
  205. }
  206. public SqlParameter CreateParameter ()
  207. {
  208. return new SqlParameter ();
  209. }
  210. internal void DeriveParameters ()
  211. {
  212. if (commandType != CommandType.StoredProcedure)
  213. throw new InvalidOperationException (String.Format ("SqlCommand DeriveParameters only supports CommandType.StoredProcedure, not CommandType.{0}", commandType));
  214. ValidateCommand ("DeriveParameters");
  215. SqlParameterCollection localParameters = new SqlParameterCollection (this);
  216. localParameters.Add ("@P1", SqlDbType.NVarChar, commandText.Length).Value = commandText;
  217. string sql = "sp_procedure_params_rowset";
  218. Connection.Tds.ExecProc (sql, localParameters.MetaParameters, 0, true);
  219. SqlDataReader reader = new SqlDataReader (this);
  220. parameters.Clear ();
  221. object[] dbValues = new object[reader.FieldCount];
  222. while (reader.Read ()) {
  223. reader.GetValues (dbValues);
  224. parameters.Add (new SqlParameter (dbValues));
  225. }
  226. reader.Close ();
  227. }
  228. private void Execute (CommandBehavior behavior, bool wantResults)
  229. {
  230. TdsMetaParameterCollection parms = Parameters.MetaParameters;
  231. if (preparedStatement == null) {
  232. bool schemaOnly = ((CommandBehavior & CommandBehavior.SchemaOnly) > 0);
  233. bool keyInfo = ((CommandBehavior & CommandBehavior.KeyInfo) > 0);
  234. StringBuilder sql1 = new StringBuilder ();
  235. StringBuilder sql2 = new StringBuilder ();
  236. if (schemaOnly || keyInfo)
  237. sql1.Append ("SET FMTONLY OFF;");
  238. if (keyInfo) {
  239. sql1.Append ("SET NO_BROWSETABLE ON;");
  240. sql2.Append ("SET NO_BROWSETABLE OFF;");
  241. }
  242. if (schemaOnly) {
  243. sql1.Append ("SET FMTONLY ON;");
  244. sql2.Append ("SET FMTONLY OFF;");
  245. }
  246. switch (CommandType) {
  247. case CommandType.StoredProcedure:
  248. if (keyInfo || schemaOnly)
  249. Connection.Tds.Execute (sql1.ToString ());
  250. Connection.Tds.ExecProc (CommandText, parms, CommandTimeout, wantResults);
  251. if (keyInfo || schemaOnly)
  252. Connection.Tds.Execute (sql2.ToString ());
  253. break;
  254. case CommandType.Text:
  255. string sql = String.Format ("{0}{1}{2}", sql1.ToString (), CommandText, sql2.ToString ());
  256. Connection.Tds.Execute (sql, parms, CommandTimeout, wantResults);
  257. break;
  258. }
  259. }
  260. else
  261. Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
  262. }
  263. public int ExecuteNonQuery ()
  264. {
  265. ValidateCommand ("ExecuteNonQuery");
  266. int result = 0;
  267. try {
  268. Execute (CommandBehavior.Default, false);
  269. // .NET documentation says that except for INSERT, UPDATE and
  270. // DELETE where the return value is the number of rows affected
  271. // for the rest of the commands the return value is -1.
  272. if ((CommandText.ToUpper().IndexOf("UPDATE")!=-1) ||
  273. (CommandText.ToUpper().IndexOf("INSERT")!=-1) ||
  274. (CommandText.ToUpper().IndexOf("DELETE")!=-1))
  275. result = Connection.Tds.RecordsAffected;
  276. else
  277. result = -1;
  278. }
  279. catch (TdsTimeoutException e) {
  280. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  281. }
  282. GetOutputParameters ();
  283. return result;
  284. }
  285. public SqlDataReader ExecuteReader ()
  286. {
  287. return ExecuteReader (CommandBehavior.Default);
  288. }
  289. public SqlDataReader ExecuteReader (CommandBehavior behavior)
  290. {
  291. ValidateCommand ("ExecuteReader");
  292. try {
  293. Execute (behavior, true);
  294. }
  295. catch (TdsTimeoutException e) {
  296. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  297. }
  298. Connection.DataReader = new SqlDataReader (this);
  299. return Connection.DataReader;
  300. }
  301. public object ExecuteScalar ()
  302. {
  303. ValidateCommand ("ExecuteScalar");
  304. try {
  305. Execute (CommandBehavior.Default, true);
  306. }
  307. catch (TdsTimeoutException e) {
  308. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  309. }
  310. if (!Connection.Tds.NextResult () || !Connection.Tds.NextRow ())
  311. return null;
  312. object result = Connection.Tds.ColumnValues [0];
  313. CloseDataReader (true);
  314. return result;
  315. }
  316. public XmlReader ExecuteXmlReader ()
  317. {
  318. ValidateCommand ("ExecuteXmlReader");
  319. try {
  320. Execute (CommandBehavior.Default, true);
  321. }
  322. catch (TdsTimeoutException e) {
  323. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  324. }
  325. SqlDataReader dataReader = new SqlDataReader (this);
  326. SqlXmlTextReader textReader = new SqlXmlTextReader (dataReader);
  327. XmlReader xmlReader = new XmlTextReader (textReader);
  328. return xmlReader;
  329. }
  330. internal void GetOutputParameters ()
  331. {
  332. IList list = Connection.Tds.OutputParameters;
  333. if (list != null && list.Count > 0) {
  334. int index = 0;
  335. foreach (SqlParameter parameter in parameters) {
  336. if (parameter.Direction != ParameterDirection.Input) {
  337. parameter.Value = list [index];
  338. index += 1;
  339. }
  340. if (index >= list.Count)
  341. break;
  342. }
  343. }
  344. }
  345. object ICloneable.Clone ()
  346. {
  347. return new SqlCommand (commandText, Connection);
  348. }
  349. IDbDataParameter IDbCommand.CreateParameter ()
  350. {
  351. return CreateParameter ();
  352. }
  353. IDataReader IDbCommand.ExecuteReader ()
  354. {
  355. return ExecuteReader ();
  356. }
  357. IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
  358. {
  359. return ExecuteReader (behavior);
  360. }
  361. public void Prepare ()
  362. {
  363. ValidateCommand ("Prepare");
  364. if (CommandType == CommandType.Text)
  365. preparedStatement = Connection.Tds.Prepare (CommandText, Parameters.MetaParameters);
  366. }
  367. public void ResetCommandTimeout ()
  368. {
  369. commandTimeout = 30;
  370. }
  371. private void Unprepare ()
  372. {
  373. Connection.Tds.Unprepare (preparedStatement);
  374. preparedStatement = null;
  375. }
  376. private void ValidateCommand (string method)
  377. {
  378. if (Connection == null)
  379. throw new InvalidOperationException (String.Format ("{0} requires a Connection object to continue.", method));
  380. if (Connection.Transaction != null && transaction != Connection.Transaction)
  381. throw new InvalidOperationException ("The Connection object does not have the same transaction as the command object.");
  382. if (Connection.State != ConnectionState.Open)
  383. throw new InvalidOperationException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
  384. if (commandText == String.Empty || commandText == null)
  385. throw new InvalidOperationException ("The command text for this Command has not been set.");
  386. if (Connection.DataReader != null)
  387. throw new InvalidOperationException ("There is already an open DataReader associated with this Connection which must be closed first.");
  388. if (Connection.XmlReader != null)
  389. throw new InvalidOperationException ("There is already an open XmlReader associated with this Connection which must be closed first.");
  390. }
  391. #endregion // Methods
  392. }
  393. }