2
0

SqlCommand.cs 12 KB

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