SqlCommand.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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. private SqlCommand(string commandText, SqlConnection connection, SqlTransaction transaction, CommandType commandType, UpdateRowSource updatedRowSource, bool designTimeVisible, int commandTimeout, SqlParameterCollection parameters)
  92. {
  93. this.commandText = commandText;
  94. this.connection = connection;
  95. this.transaction = transaction;
  96. this.commandType = commandType;
  97. this.updatedRowSource = updatedRowSource;
  98. this.designTimeVisible = designTimeVisible;
  99. this.commandTimeout = commandTimeout;
  100. this.parameters = new SqlParameterCollection(this);
  101. for (int i = 0;i < parameters.Count;i++)
  102. this.parameters.Add(((ICloneable)parameters[i]).Clone());
  103. }
  104. #endregion // Constructors
  105. #region Properties
  106. internal CommandBehavior CommandBehavior {
  107. get { return behavior; }
  108. }
  109. [DataCategory ("Data")]
  110. [DataSysDescription ("Command text to execute.")]
  111. [DefaultValue ("")]
  112. [EditorAttribute ("Microsoft.VSDesigner.Data.SQL.Design.SqlCommandTextEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  113. [RefreshProperties (RefreshProperties.All)]
  114. public string CommandText {
  115. get { return commandText; }
  116. set {
  117. if (value != commandText && preparedStatement != null)
  118. Unprepare ();
  119. commandText = value;
  120. }
  121. }
  122. [DataSysDescription ("Time to wait for command to execute.")]
  123. [DefaultValue (30)]
  124. public int CommandTimeout {
  125. get { return commandTimeout; }
  126. set {
  127. if (commandTimeout < 0)
  128. throw new ArgumentException ("The property value assigned is less than 0.");
  129. commandTimeout = value;
  130. }
  131. }
  132. [DataCategory ("Data")]
  133. [DataSysDescription ("How to interpret the CommandText.")]
  134. [DefaultValue (CommandType.Text)]
  135. [RefreshProperties (RefreshProperties.All)]
  136. public CommandType CommandType {
  137. get { return commandType; }
  138. set {
  139. if (value == CommandType.TableDirect)
  140. throw new ArgumentException ("CommandType.TableDirect is not supported by the Mono SqlClient Data Provider.");
  141. commandType = value;
  142. }
  143. }
  144. [DataCategory ("Behavior")]
  145. [DefaultValue (null)]
  146. [DataSysDescription ("Connection used by the command.")]
  147. [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )] public SqlConnection Connection {
  148. get { return connection; }
  149. set {
  150. if (transaction != null && connection.Transaction != null && connection.Transaction.IsOpen)
  151. throw new InvalidOperationException ("The Connection property was changed while a transaction was in progress.");
  152. transaction = null;
  153. connection = value;
  154. }
  155. }
  156. [Browsable (false)]
  157. [DefaultValue (true)]
  158. [DesignOnly (true)]
  159. public bool DesignTimeVisible {
  160. get { return designTimeVisible; }
  161. set { designTimeVisible = value; }
  162. }
  163. [DataCategory ("Data")]
  164. [DataSysDescription ("The parameters collection.")]
  165. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  166. public SqlParameterCollection Parameters {
  167. get { return parameters; }
  168. }
  169. internal ITds Tds {
  170. get { return Connection.Tds; }
  171. }
  172. IDbConnection IDbCommand.Connection {
  173. get { return Connection; }
  174. set {
  175. if (!(value is SqlConnection))
  176. throw new InvalidCastException ("The value was not a valid SqlConnection.");
  177. Connection = (SqlConnection) value;
  178. }
  179. }
  180. IDataParameterCollection IDbCommand.Parameters {
  181. get { return Parameters; }
  182. }
  183. IDbTransaction IDbCommand.Transaction {
  184. get { return Transaction; }
  185. set {
  186. if (!(value is SqlTransaction))
  187. throw new ArgumentException ();
  188. Transaction = (SqlTransaction) value;
  189. }
  190. }
  191. [Browsable (false)]
  192. [DataSysDescription ("The transaction used by the command.")]
  193. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  194. public SqlTransaction Transaction {
  195. get { return transaction; }
  196. set { transaction = value; }
  197. }
  198. [DataCategory ("Behavior")]
  199. [DataSysDescription ("When used by a DataAdapter.Update, how command results are applied to the current DataRow.")]
  200. [DefaultValue (UpdateRowSource.Both)]
  201. public UpdateRowSource UpdatedRowSource {
  202. get { return updatedRowSource; }
  203. set { updatedRowSource = value; }
  204. }
  205. #endregion // Fields
  206. #region Methods
  207. public void Cancel ()
  208. {
  209. if (Connection == null || Connection.Tds == null)
  210. return;
  211. Connection.Tds.Cancel ();
  212. }
  213. internal void CloseDataReader (bool moreResults)
  214. {
  215. Connection.DataReader = null;
  216. if ((behavior & CommandBehavior.CloseConnection) != 0)
  217. Connection.Close ();
  218. }
  219. public SqlParameter CreateParameter ()
  220. {
  221. return new SqlParameter ();
  222. }
  223. internal void DeriveParameters ()
  224. {
  225. if (commandType != CommandType.StoredProcedure)
  226. throw new InvalidOperationException (String.Format ("SqlCommand DeriveParameters only supports CommandType.StoredProcedure, not CommandType.{0}", commandType));
  227. ValidateCommand ("DeriveParameters");
  228. SqlParameterCollection localParameters = new SqlParameterCollection (this);
  229. localParameters.Add ("@P1", SqlDbType.NVarChar, commandText.Length).Value = commandText;
  230. string sql = "sp_procedure_params_rowset";
  231. Connection.Tds.ExecProc (sql, localParameters.MetaParameters, 0, true);
  232. SqlDataReader reader = new SqlDataReader (this);
  233. parameters.Clear ();
  234. object[] dbValues = new object[reader.FieldCount];
  235. while (reader.Read ()) {
  236. reader.GetValues (dbValues);
  237. parameters.Add (new SqlParameter (dbValues));
  238. }
  239. reader.Close ();
  240. }
  241. private void Execute (CommandBehavior behavior, bool wantResults)
  242. {
  243. TdsMetaParameterCollection parms = Parameters.MetaParameters;
  244. if (preparedStatement == null) {
  245. bool schemaOnly = ((behavior & CommandBehavior.SchemaOnly) > 0);
  246. bool keyInfo = ((behavior & CommandBehavior.KeyInfo) > 0);
  247. StringBuilder sql1 = new StringBuilder ();
  248. StringBuilder sql2 = new StringBuilder ();
  249. if (schemaOnly || keyInfo)
  250. sql1.Append ("SET FMTONLY OFF;");
  251. if (keyInfo) {
  252. sql1.Append ("SET NO_BROWSETABLE ON;");
  253. sql2.Append ("SET NO_BROWSETABLE OFF;");
  254. }
  255. if (schemaOnly) {
  256. sql1.Append ("SET FMTONLY ON;");
  257. sql2.Append ("SET FMTONLY OFF;");
  258. }
  259. switch (CommandType) {
  260. case CommandType.StoredProcedure:
  261. if (keyInfo || schemaOnly)
  262. Connection.Tds.Execute (sql1.ToString ());
  263. Connection.Tds.ExecProc (CommandText, parms, CommandTimeout, wantResults);
  264. if (keyInfo || schemaOnly)
  265. Connection.Tds.Execute (sql2.ToString ());
  266. break;
  267. case CommandType.Text:
  268. string sql = String.Format ("{0}{1}{2}", sql1.ToString (), CommandText, sql2.ToString ());
  269. Connection.Tds.Execute (sql, parms, CommandTimeout, wantResults);
  270. break;
  271. }
  272. }
  273. else
  274. Connection.Tds.ExecPrepared (preparedStatement, parms, CommandTimeout, wantResults);
  275. }
  276. public int ExecuteNonQuery ()
  277. {
  278. ValidateCommand ("ExecuteNonQuery");
  279. int result = 0;
  280. try {
  281. Execute (CommandBehavior.Default, false);
  282. if (commandType == CommandType.StoredProcedure)
  283. result = -1;
  284. else {
  285. // .NET documentation says that except for INSERT, UPDATE and
  286. // DELETE where the return value is the number of rows affected
  287. // for the rest of the commands the return value is -1.
  288. if ((CommandText.ToUpper().IndexOf("UPDATE")!=-1) ||
  289. (CommandText.ToUpper().IndexOf("INSERT")!=-1) ||
  290. (CommandText.ToUpper().IndexOf("DELETE")!=-1))
  291. result = Connection.Tds.RecordsAffected;
  292. else
  293. result = -1;
  294. }
  295. }
  296. catch (TdsTimeoutException e) {
  297. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  298. }
  299. GetOutputParameters ();
  300. return result;
  301. }
  302. public SqlDataReader ExecuteReader ()
  303. {
  304. return ExecuteReader (CommandBehavior.Default);
  305. }
  306. public SqlDataReader ExecuteReader (CommandBehavior behavior)
  307. {
  308. ValidateCommand ("ExecuteReader");
  309. try {
  310. Execute (behavior, true);
  311. }
  312. catch (TdsTimeoutException e) {
  313. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  314. }
  315. Connection.DataReader = new SqlDataReader (this);
  316. return Connection.DataReader;
  317. }
  318. public object ExecuteScalar ()
  319. {
  320. ValidateCommand ("ExecuteScalar");
  321. try {
  322. Execute (CommandBehavior.Default, true);
  323. }
  324. catch (TdsTimeoutException e) {
  325. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  326. }
  327. if (!Connection.Tds.NextResult () || !Connection.Tds.NextRow ())
  328. return null;
  329. object result = Connection.Tds.ColumnValues [0];
  330. CloseDataReader (true);
  331. return result;
  332. }
  333. public XmlReader ExecuteXmlReader ()
  334. {
  335. ValidateCommand ("ExecuteXmlReader");
  336. try {
  337. Execute (CommandBehavior.Default, true);
  338. }
  339. catch (TdsTimeoutException e) {
  340. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  341. }
  342. SqlDataReader dataReader = new SqlDataReader (this);
  343. SqlXmlTextReader textReader = new SqlXmlTextReader (dataReader);
  344. XmlReader xmlReader = new XmlTextReader (textReader);
  345. return xmlReader;
  346. }
  347. internal void GetOutputParameters ()
  348. {
  349. IList list = Connection.Tds.OutputParameters;
  350. if (list != null && list.Count > 0) {
  351. int index = 0;
  352. foreach (SqlParameter parameter in parameters) {
  353. if (parameter.Direction != ParameterDirection.Input) {
  354. parameter.Value = list [index];
  355. index += 1;
  356. }
  357. if (index >= list.Count)
  358. break;
  359. }
  360. }
  361. }
  362. object ICloneable.Clone ()
  363. {
  364. return new SqlCommand (commandText, connection, transaction, commandType, updatedRowSource, designTimeVisible, commandTimeout, parameters);
  365. }
  366. IDbDataParameter IDbCommand.CreateParameter ()
  367. {
  368. return CreateParameter ();
  369. }
  370. IDataReader IDbCommand.ExecuteReader ()
  371. {
  372. return ExecuteReader ();
  373. }
  374. IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
  375. {
  376. return ExecuteReader (behavior);
  377. }
  378. public void Prepare ()
  379. {
  380. ValidateCommand ("Prepare");
  381. if (CommandType == CommandType.Text)
  382. preparedStatement = Connection.Tds.Prepare (CommandText, Parameters.MetaParameters);
  383. }
  384. public void ResetCommandTimeout ()
  385. {
  386. commandTimeout = 30;
  387. }
  388. private void Unprepare ()
  389. {
  390. Connection.Tds.Unprepare (preparedStatement);
  391. preparedStatement = null;
  392. }
  393. private void ValidateCommand (string method)
  394. {
  395. if (Connection == null)
  396. throw new InvalidOperationException (String.Format ("{0} requires a Connection object to continue.", method));
  397. if (Connection.Transaction != null && transaction != Connection.Transaction)
  398. throw new InvalidOperationException ("The Connection object does not have the same transaction as the command object.");
  399. if (Connection.State != ConnectionState.Open)
  400. throw new InvalidOperationException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
  401. if (commandText == String.Empty || commandText == null)
  402. throw new InvalidOperationException ("The command text for this Command has not been set.");
  403. if (Connection.DataReader != null)
  404. throw new InvalidOperationException ("There is already an open DataReader associated with this Connection which must be closed first.");
  405. if (Connection.XmlReader != null)
  406. throw new InvalidOperationException ("There is already an open XmlReader associated with this Connection which must be closed first.");
  407. }
  408. #endregion // Methods
  409. }
  410. }