SqlCommand.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. //
  9. // (C) Ximian, Inc 2002 http://www.ximian.com/
  10. // (C) Daniel Morgan, 2002
  11. // Copyright (C) Tim Coleman, 2002
  12. //
  13. using Mono.Data.TdsClient.Internal;
  14. using System;
  15. using System.Collections;
  16. using System.Collections.Specialized;
  17. using System.ComponentModel;
  18. using System.Data;
  19. using System.Data.Common;
  20. using System.Runtime.InteropServices;
  21. using System.Text;
  22. using System.Xml;
  23. namespace System.Data.SqlClient {
  24. public sealed class SqlCommand : Component, IDbCommand, ICloneable
  25. {
  26. #region Fields
  27. int commandTimeout;
  28. bool designTimeVisible;
  29. string commandText;
  30. CommandType commandType;
  31. SqlConnection connection;
  32. SqlTransaction transaction;
  33. UpdateRowSource updatedRowSource;
  34. CommandBehavior behavior = CommandBehavior.Default;
  35. NameValueCollection preparedStatements = new NameValueCollection ();
  36. SqlParameterCollection parameters;
  37. #endregion // Fields
  38. #region Constructors
  39. public SqlCommand()
  40. : this (String.Empty, null, null)
  41. {
  42. }
  43. public SqlCommand (string commandText)
  44. : this (commandText, null, null)
  45. {
  46. commandText = commandText;
  47. }
  48. public SqlCommand (string commandText, SqlConnection connection)
  49. : this (commandText, connection, null)
  50. {
  51. Connection = connection;
  52. }
  53. public SqlCommand (string commandText, SqlConnection connection, SqlTransaction transaction)
  54. {
  55. this.commandText = commandText;
  56. this.connection = connection;
  57. this.transaction = transaction;
  58. this.commandType = CommandType.Text;
  59. this.updatedRowSource = UpdateRowSource.Both;
  60. this.designTimeVisible = false;
  61. this.commandTimeout = 30;
  62. parameters = new SqlParameterCollection (this);
  63. }
  64. #endregion // Constructors
  65. #region Properties
  66. internal CommandBehavior CommandBehavior {
  67. get { return behavior; }
  68. }
  69. [DataSysDescription ("Command text to execute.")]
  70. [DefaultValue ("")]
  71. [RefreshProperties (RefreshProperties.All)]
  72. public string CommandText {
  73. get { return commandText; }
  74. set { commandText = value; }
  75. }
  76. [DataSysDescription ("Time to wait for command to execute.")]
  77. [DefaultValue (30)]
  78. public int CommandTimeout {
  79. get { return commandTimeout; }
  80. set {
  81. if (commandTimeout < 0)
  82. throw new ArgumentException ("The property value assigned is less than 0.");
  83. commandTimeout = value;
  84. }
  85. }
  86. [DataSysDescription ("How to interpret the CommandText.")]
  87. [DefaultValue (CommandType.Text)]
  88. [RefreshProperties (RefreshProperties.All)]
  89. public CommandType CommandType {
  90. get { return commandType; }
  91. set { commandType = value; }
  92. }
  93. [DefaultValue (null)]
  94. [DataSysDescription ("Connection used by the command.")]
  95. public SqlConnection Connection {
  96. get { return connection; }
  97. set {
  98. if (transaction != null && connection.Transaction != null && connection.Transaction.IsOpen)
  99. throw new InvalidOperationException ("The Connection property was changed while a transaction was in progress.");
  100. transaction = null;
  101. connection = value;
  102. }
  103. }
  104. [Browsable (false)]
  105. [DefaultValue (true)]
  106. [DesignOnly (true)]
  107. public bool DesignTimeVisible {
  108. get { return designTimeVisible; }
  109. set { designTimeVisible = value; }
  110. }
  111. [DataSysDescription ("The parameters collection.")]
  112. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  113. public SqlParameterCollection Parameters {
  114. get { return parameters; }
  115. }
  116. internal ITds Tds {
  117. get { return connection.Tds; }
  118. }
  119. IDbConnection IDbCommand.Connection {
  120. get { return Connection; }
  121. set {
  122. if (!(value is SqlConnection))
  123. throw new InvalidCastException ("The value was not a valid SqlConnection.");
  124. Connection = (SqlConnection) value;
  125. }
  126. }
  127. IDataParameterCollection IDbCommand.Parameters {
  128. get { return Parameters; }
  129. }
  130. IDbTransaction IDbCommand.Transaction {
  131. get { return Transaction; }
  132. set {
  133. if (!(value is SqlTransaction))
  134. throw new ArgumentException ();
  135. Transaction = (SqlTransaction) value;
  136. }
  137. }
  138. [Browsable (false)]
  139. [DataSysDescription ("The transaction used by the command.")]
  140. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  141. public SqlTransaction Transaction {
  142. get { return transaction; }
  143. set { transaction = value; }
  144. }
  145. [DataSysDescription ("When used by a DataAdapter.Update, how command results are applied to the current DataRow.")]
  146. [DefaultValue (UpdateRowSource.Both)]
  147. public UpdateRowSource UpdatedRowSource {
  148. get { return updatedRowSource; }
  149. set { updatedRowSource = value; }
  150. }
  151. #endregion // Fields
  152. #region Methods
  153. private string BuildCommand ()
  154. {
  155. string statementHandle = preparedStatements [commandText];
  156. if (statementHandle != null) {
  157. string proc = String.Format ("sp_execute {0}", statementHandle);
  158. if (parameters.Count > 0)
  159. proc += ",";
  160. return BuildProcedureCall (proc, parameters);
  161. }
  162. if (commandType == CommandType.StoredProcedure)
  163. return BuildProcedureCall (commandText, parameters);
  164. string sql = String.Empty;
  165. if ((behavior & CommandBehavior.KeyInfo) > 0)
  166. sql += "SET FMTONLY OFF; SET NO_BROWSETABLE ON;";
  167. if ((behavior & CommandBehavior.SchemaOnly) > 0)
  168. sql += "SET FMTONLY ON;";
  169. switch (commandType) {
  170. case CommandType.Text :
  171. sql += commandText;
  172. break;
  173. case CommandType.TableDirect :
  174. sql += String.Format ("select * from {0}", commandText);
  175. break;
  176. default:
  177. throw new InvalidOperationException ("The CommandType was invalid.");
  178. }
  179. return BuildExec (sql);
  180. }
  181. private string BuildExec (string sql)
  182. {
  183. StringBuilder parms = new StringBuilder ();
  184. foreach (SqlParameter parameter in parameters) {
  185. if (parms.Length > 0)
  186. parms.Append (", ");
  187. parms.Append (parameter.Prepare (parameter.ParameterName));
  188. if (parameter.Direction == ParameterDirection.Output)
  189. parms.Append (" output");
  190. }
  191. SqlParameterCollection localParameters = new SqlParameterCollection (this);
  192. SqlParameter parm;
  193. parm = new SqlParameter ("@P1", SqlDbType.NVarChar);
  194. parm.Value = sql;
  195. parm.Size = ((string) parm.Value).Length;
  196. localParameters.Add (parm);
  197. if (parameters.Count > 0) {
  198. parm = new SqlParameter ("@P2", SqlDbType.NVarChar);
  199. parm.Value = parms.ToString ();
  200. parm.Size = ((string) parm.Value).Length;
  201. localParameters.Add (parm);
  202. }
  203. foreach (SqlParameter p in parameters)
  204. localParameters.Add (p);
  205. return BuildProcedureCall ("sp_executesql", localParameters);
  206. }
  207. private string BuildPrepare ()
  208. {
  209. StringBuilder parms = new StringBuilder ();
  210. foreach (SqlParameter parameter in parameters) {
  211. if (parms.Length > 0)
  212. parms.Append (", ");
  213. parms.Append (parameter.Prepare (parameter.ParameterName));
  214. if (parameter.Direction == ParameterDirection.Output)
  215. parms.Append (" output");
  216. }
  217. SqlParameterCollection localParameters = new SqlParameterCollection (this);
  218. SqlParameter parm;
  219. parm = new SqlParameter ("@P1", SqlDbType.Int);
  220. parm.Direction = ParameterDirection.Output;
  221. localParameters.Add (parm);
  222. parm = new SqlParameter ("@P2", SqlDbType.NVarChar);
  223. parm.Value = parms.ToString ();
  224. parm.Size = ((string) parm.Value).Length;
  225. localParameters.Add (parm);
  226. parm = new SqlParameter ("@P3", SqlDbType.NVarChar);
  227. parm.Value = commandText;
  228. parm.Size = ((string) parm.Value).Length;
  229. localParameters.Add (parm);
  230. return BuildProcedureCall ("sp_prepare", localParameters);
  231. }
  232. private static string BuildProcedureCall (string procedure, SqlParameterCollection parameters)
  233. {
  234. StringBuilder parms = new StringBuilder ();
  235. StringBuilder declarations = new StringBuilder ();
  236. StringBuilder outParms = new StringBuilder ();
  237. StringBuilder set = new StringBuilder ();
  238. int index = 1;
  239. foreach (SqlParameter parameter in parameters) {
  240. string parmName = String.Format ("@P{0}", index);
  241. switch (parameter.Direction) {
  242. case ParameterDirection.Input :
  243. if (parms.Length > 0)
  244. parms.Append (", ");
  245. parms.Append (FormatParameter (parameter));
  246. break;
  247. case ParameterDirection.Output :
  248. if (parms.Length > 0)
  249. parms.Append (", ");
  250. parms.Append (parmName);
  251. parms.Append (" output");
  252. if (outParms.Length > 0) {
  253. outParms.Append (", ");
  254. declarations.Append (", ");
  255. }
  256. else {
  257. outParms.Append ("select ");
  258. declarations.Append ("declare ");
  259. }
  260. declarations.Append (parameter.Prepare (parmName));
  261. set.Append (String.Format ("set {0}=NULL\n", parmName));
  262. outParms.Append (parmName);
  263. break;
  264. default :
  265. throw new NotImplementedException ("Only support input and output parameters.");
  266. }
  267. index += 1;
  268. }
  269. return String.Format ("{0}\n{1}{2} {3}\n{4}", declarations.ToString (), set.ToString (), procedure, parms.ToString (), outParms.ToString ());
  270. }
  271. public void Cancel ()
  272. {
  273. if (connection == null || connection.Tds == null)
  274. return;
  275. connection.Tds.Cancel ();
  276. }
  277. internal void CloseDataReader (bool moreResults)
  278. {
  279. GetOutputParameters ();
  280. connection.DataReader = null;
  281. if ((behavior & CommandBehavior.CloseConnection) != 0)
  282. connection.Close ();
  283. }
  284. public SqlParameter CreateParameter ()
  285. {
  286. return new SqlParameter ();
  287. }
  288. internal void DeriveParameters ()
  289. {
  290. if (commandType != CommandType.StoredProcedure)
  291. throw new InvalidOperationException (String.Format ("SqlCommand DeriveParameters only supports CommandType.StoredProcedure, not CommandType.{0}", commandType));
  292. ValidateCommand ("DeriveParameters");
  293. SqlParameterCollection localParameters = new SqlParameterCollection (this);
  294. localParameters.Add ("@P1", SqlDbType.NVarChar, commandText.Length).Value = commandText;
  295. connection.Tds.ExecuteQuery (BuildProcedureCall ("sp_procedure_params_rowset", localParameters));
  296. SqlDataReader reader = new SqlDataReader (this);
  297. parameters.Clear ();
  298. object[] dbValues = new object[reader.FieldCount];
  299. while (reader.Read ()) {
  300. reader.GetValues (dbValues);
  301. parameters.Add (new SqlParameter (dbValues));
  302. }
  303. reader.Close ();
  304. }
  305. public int ExecuteNonQuery ()
  306. {
  307. ValidateCommand ("ExecuteNonQuery");
  308. int result = connection.Tds.ExecuteNonQuery (BuildCommand ());
  309. GetOutputParameters ();
  310. return result;
  311. }
  312. public SqlDataReader ExecuteReader ()
  313. {
  314. return ExecuteReader (CommandBehavior.Default);
  315. }
  316. public SqlDataReader ExecuteReader (CommandBehavior behavior)
  317. {
  318. ValidateCommand ("ExecuteReader");
  319. this.behavior = behavior;
  320. connection.Tds.ExecuteQuery (BuildCommand ());
  321. connection.DataReader = new SqlDataReader (this);
  322. return connection.DataReader;
  323. }
  324. public object ExecuteScalar ()
  325. {
  326. ValidateCommand ("ExecuteScalar");
  327. connection.Tds.ExecuteQuery (BuildCommand ());
  328. bool moreResults = connection.Tds.NextResult ();
  329. if (!moreResults)
  330. return null;
  331. moreResults = connection.Tds.NextRow ();
  332. if (!moreResults)
  333. return null;
  334. object result = connection.Tds.ColumnValues[0];
  335. CloseDataReader (true);
  336. return result;
  337. }
  338. public XmlReader ExecuteXmlReader ()
  339. {
  340. ValidateCommand ("ExecuteXmlReader");
  341. connection.Tds.ExecuteQuery (BuildCommand ());
  342. SqlDataReader dataReader = new SqlDataReader (this);
  343. SqlXmlTextReader textReader = new SqlXmlTextReader (dataReader);
  344. XmlReader xmlReader = new XmlTextReader (textReader);
  345. return xmlReader;
  346. }
  347. static string FormatParameter (SqlParameter parameter)
  348. {
  349. if (parameter.Value == null)
  350. return "NULL";
  351. switch (parameter.SqlDbType) {
  352. case SqlDbType.BigInt :
  353. case SqlDbType.Bit :
  354. case SqlDbType.Decimal :
  355. case SqlDbType.Float :
  356. case SqlDbType.Int :
  357. case SqlDbType.Money :
  358. case SqlDbType.Real :
  359. case SqlDbType.SmallInt :
  360. case SqlDbType.SmallMoney :
  361. case SqlDbType.TinyInt :
  362. return parameter.Value.ToString ();
  363. case SqlDbType.NVarChar :
  364. case SqlDbType.NChar :
  365. return String.Format ("N'{0}'", parameter.Value.ToString ().Replace ("'", "''"));
  366. default:
  367. return String.Format ("'{0}'", parameter.Value.ToString ().Replace ("'", "''"));
  368. }
  369. }
  370. private void GetOutputParameters ()
  371. {
  372. connection.Tds.SkipToEnd ();
  373. IList list = connection.Tds.ColumnValues;
  374. if (list != null && list.Count > 0) {
  375. int index = 0;
  376. foreach (SqlParameter parameter in parameters) {
  377. if (parameter.Direction != ParameterDirection.Input) {
  378. parameter.Value = list [index];
  379. index += 1;
  380. }
  381. if (index >= list.Count)
  382. break;
  383. }
  384. }
  385. }
  386. object ICloneable.Clone ()
  387. {
  388. return new SqlCommand (commandText, connection);
  389. }
  390. IDbDataParameter IDbCommand.CreateParameter ()
  391. {
  392. return CreateParameter ();
  393. }
  394. IDataReader IDbCommand.ExecuteReader ()
  395. {
  396. return ExecuteReader ();
  397. }
  398. IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
  399. {
  400. return ExecuteReader (behavior);
  401. }
  402. void IDisposable.Dispose ()
  403. {
  404. Console.WriteLine ("Disposing");
  405. Dispose (true);
  406. }
  407. public void Prepare ()
  408. {
  409. ValidateCommand ("Prepare");
  410. connection.Tds.ExecuteNonQuery (BuildPrepare ());
  411. if (connection.Tds.OutputParameters.Count == 0 || connection.Tds.OutputParameters[0] == null)
  412. throw new Exception ("Could not prepare the statement.");
  413. preparedStatements [commandText] = ((int) connection.Tds.OutputParameters [0]).ToString ();
  414. }
  415. public void ResetCommandTimeout ()
  416. {
  417. commandTimeout = 30;
  418. }
  419. private void ValidateCommand (string method)
  420. {
  421. if (connection == null)
  422. throw new InvalidOperationException (String.Format ("{0} requires a Connection object to continue.", method));
  423. if (connection.Transaction != null && transaction != connection.Transaction)
  424. throw new InvalidOperationException ("The Connection object does not have the same transaction as the command object.");
  425. if (connection.State != ConnectionState.Open)
  426. throw new InvalidOperationException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
  427. if (commandText == String.Empty || commandText == null)
  428. throw new InvalidOperationException ("The command text for this Command has not been set.");
  429. if (connection.DataReader != null)
  430. throw new InvalidOperationException ("There is already an open DataReader associated with this Connection which must be closed first.");
  431. if (connection.XmlReader != null)
  432. throw new InvalidOperationException ("There is already an open XmlReader associated with this Connection which must be closed first.");
  433. }
  434. #endregion // Methods
  435. }
  436. }