SqlCommand.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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 {
  92. if (value == CommandType.TableDirect)
  93. throw new ArgumentException ("CommandType.TableDirect is not supported by the Mono SqlClient Data Provider.");
  94. commandType = value;
  95. }
  96. }
  97. [DefaultValue (null)]
  98. [DataSysDescription ("Connection used by the command.")]
  99. public SqlConnection Connection {
  100. get { return connection; }
  101. set {
  102. if (transaction != null && connection.Transaction != null && connection.Transaction.IsOpen)
  103. throw new InvalidOperationException ("The Connection property was changed while a transaction was in progress.");
  104. transaction = null;
  105. connection = value;
  106. }
  107. }
  108. [Browsable (false)]
  109. [DefaultValue (true)]
  110. [DesignOnly (true)]
  111. public bool DesignTimeVisible {
  112. get { return designTimeVisible; }
  113. set { designTimeVisible = value; }
  114. }
  115. [DataSysDescription ("The parameters collection.")]
  116. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  117. public SqlParameterCollection Parameters {
  118. get { return parameters; }
  119. }
  120. internal ITds Tds {
  121. get { return Connection.Tds; }
  122. }
  123. IDbConnection IDbCommand.Connection {
  124. get { return Connection; }
  125. set {
  126. if (!(value is SqlConnection))
  127. throw new InvalidCastException ("The value was not a valid SqlConnection.");
  128. Connection = (SqlConnection) value;
  129. }
  130. }
  131. IDataParameterCollection IDbCommand.Parameters {
  132. get { return Parameters; }
  133. }
  134. IDbTransaction IDbCommand.Transaction {
  135. get { return Transaction; }
  136. set {
  137. if (!(value is SqlTransaction))
  138. throw new ArgumentException ();
  139. Transaction = (SqlTransaction) value;
  140. }
  141. }
  142. [Browsable (false)]
  143. [DataSysDescription ("The transaction used by the command.")]
  144. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  145. public SqlTransaction Transaction {
  146. get { return transaction; }
  147. set { transaction = value; }
  148. }
  149. [DataSysDescription ("When used by a DataAdapter.Update, how command results are applied to the current DataRow.")]
  150. [DefaultValue (UpdateRowSource.Both)]
  151. public UpdateRowSource UpdatedRowSource {
  152. get { return updatedRowSource; }
  153. set { updatedRowSource = value; }
  154. }
  155. #endregion // Fields
  156. #region Methods
  157. private string BuildCommand ()
  158. {
  159. string statementHandle = preparedStatements [commandText];
  160. if (statementHandle != null) {
  161. string proc = String.Format ("sp_execute {0}", statementHandle);
  162. if (parameters.Count > 0)
  163. proc += ",";
  164. return BuildProcedureCall (proc, parameters);
  165. }
  166. if (commandType == CommandType.StoredProcedure)
  167. return BuildProcedureCall (commandText, parameters);
  168. string sql = String.Empty;
  169. if ((behavior & CommandBehavior.KeyInfo) > 0)
  170. sql += "SET FMTONLY OFF; SET NO_BROWSETABLE ON;";
  171. if ((behavior & CommandBehavior.SchemaOnly) > 0)
  172. sql += "SET FMTONLY ON;";
  173. switch (commandType) {
  174. case CommandType.Text :
  175. sql += commandText;
  176. break;
  177. default:
  178. throw new InvalidOperationException ("The CommandType was invalid.");
  179. }
  180. return BuildExec (sql);
  181. }
  182. private string BuildExec (string sql)
  183. {
  184. StringBuilder parms = new StringBuilder ();
  185. foreach (SqlParameter parameter in parameters) {
  186. if (parms.Length > 0)
  187. parms.Append (", ");
  188. parms.Append (parameter.Prepare (parameter.ParameterName));
  189. if (parameter.Direction == ParameterDirection.Output)
  190. parms.Append (" output");
  191. }
  192. SqlParameterCollection localParameters = new SqlParameterCollection (this);
  193. SqlParameter parm;
  194. parm = new SqlParameter ("@P1", SqlDbType.NVarChar);
  195. parm.Value = sql;
  196. parm.Size = ((string) parm.Value).Length;
  197. localParameters.Add (parm);
  198. if (parameters.Count > 0) {
  199. parm = new SqlParameter ("@P2", SqlDbType.NVarChar);
  200. parm.Value = parms.ToString ();
  201. parm.Size = ((string) parm.Value).Length;
  202. localParameters.Add (parm);
  203. }
  204. foreach (SqlParameter p in parameters)
  205. localParameters.Add (p);
  206. return BuildProcedureCall ("sp_executesql", localParameters);
  207. }
  208. private string BuildPrepare ()
  209. {
  210. StringBuilder parms = new StringBuilder ();
  211. foreach (SqlParameter parameter in parameters) {
  212. if (parms.Length > 0)
  213. parms.Append (", ");
  214. parms.Append (parameter.Prepare (parameter.ParameterName));
  215. if (parameter.Direction == ParameterDirection.Output)
  216. parms.Append (" output");
  217. }
  218. SqlParameterCollection localParameters = new SqlParameterCollection (this);
  219. SqlParameter parm;
  220. parm = new SqlParameter ("@P1", SqlDbType.Int);
  221. parm.Direction = ParameterDirection.Output;
  222. localParameters.Add (parm);
  223. parm = new SqlParameter ("@P2", SqlDbType.NVarChar);
  224. parm.Value = parms.ToString ();
  225. parm.Size = ((string) parm.Value).Length;
  226. localParameters.Add (parm);
  227. parm = new SqlParameter ("@P3", SqlDbType.NVarChar);
  228. parm.Value = commandText;
  229. parm.Size = ((string) parm.Value).Length;
  230. localParameters.Add (parm);
  231. return BuildProcedureCall ("sp_prepare", localParameters);
  232. }
  233. private static string BuildProcedureCall (string procedure, SqlParameterCollection parameters)
  234. {
  235. StringBuilder parms = new StringBuilder ();
  236. StringBuilder declarations = new StringBuilder ();
  237. StringBuilder outParms = new StringBuilder ();
  238. StringBuilder set = new StringBuilder ();
  239. int index = 1;
  240. foreach (SqlParameter parameter in parameters) {
  241. string parmName = String.Format ("@P{0}", index);
  242. switch (parameter.Direction) {
  243. case ParameterDirection.Input :
  244. if (parms.Length > 0)
  245. parms.Append (", ");
  246. parms.Append (FormatParameter (parameter));
  247. break;
  248. case ParameterDirection.Output :
  249. if (parms.Length > 0)
  250. parms.Append (", ");
  251. parms.Append (parmName);
  252. parms.Append (" output");
  253. if (outParms.Length > 0) {
  254. outParms.Append (", ");
  255. declarations.Append (", ");
  256. }
  257. else {
  258. outParms.Append ("select ");
  259. declarations.Append ("declare ");
  260. }
  261. declarations.Append (parameter.Prepare (parmName));
  262. set.Append (String.Format ("set {0}=NULL\n", parmName));
  263. outParms.Append (parmName);
  264. break;
  265. default :
  266. throw new NotImplementedException ("Only support input and output parameters.");
  267. }
  268. index += 1;
  269. }
  270. return String.Format ("{0}\n{1}{2} {3}\n{4}", declarations.ToString (), set.ToString (), procedure, parms.ToString (), outParms.ToString ());
  271. }
  272. public void Cancel ()
  273. {
  274. if (Connection == null || Connection.Tds == null)
  275. return;
  276. Connection.Tds.Cancel ();
  277. }
  278. internal void CloseDataReader (bool moreResults)
  279. {
  280. GetOutputParameters ();
  281. Connection.DataReader = null;
  282. if ((behavior & CommandBehavior.CloseConnection) != 0)
  283. Connection.Close ();
  284. }
  285. public SqlParameter CreateParameter ()
  286. {
  287. return new SqlParameter ();
  288. }
  289. internal void DeriveParameters ()
  290. {
  291. if (commandType != CommandType.StoredProcedure)
  292. throw new InvalidOperationException (String.Format ("SqlCommand DeriveParameters only supports CommandType.StoredProcedure, not CommandType.{0}", commandType));
  293. ValidateCommand ("DeriveParameters");
  294. SqlParameterCollection localParameters = new SqlParameterCollection (this);
  295. localParameters.Add ("@P1", SqlDbType.NVarChar, commandText.Length).Value = commandText;
  296. Connection.Tds.ExecuteQuery (BuildProcedureCall ("sp_procedure_params_rowset", localParameters));
  297. SqlDataReader reader = new SqlDataReader (this);
  298. parameters.Clear ();
  299. object[] dbValues = new object[reader.FieldCount];
  300. while (reader.Read ()) {
  301. reader.GetValues (dbValues);
  302. parameters.Add (new SqlParameter (dbValues));
  303. }
  304. reader.Close ();
  305. }
  306. public int ExecuteNonQuery ()
  307. {
  308. ValidateCommand ("ExecuteNonQuery");
  309. string sql = String.Empty;
  310. int result = 0;
  311. if (Parameters.Count > 0)
  312. sql = BuildCommand ();
  313. else
  314. sql = CommandText;
  315. try {
  316. result = Connection.Tds.ExecuteNonQuery (sql, CommandTimeout);
  317. }
  318. catch (TdsTimeoutException e) {
  319. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  320. }
  321. GetOutputParameters ();
  322. return result;
  323. }
  324. public SqlDataReader ExecuteReader ()
  325. {
  326. return ExecuteReader (CommandBehavior.Default);
  327. }
  328. public SqlDataReader ExecuteReader (CommandBehavior behavior)
  329. {
  330. ValidateCommand ("ExecuteReader");
  331. this.behavior = behavior;
  332. try {
  333. Connection.Tds.ExecuteQuery (BuildCommand (), CommandTimeout);
  334. }
  335. catch (TdsTimeoutException e) {
  336. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  337. }
  338. Connection.DataReader = new SqlDataReader (this);
  339. return Connection.DataReader;
  340. }
  341. public object ExecuteScalar ()
  342. {
  343. ValidateCommand ("ExecuteScalar");
  344. try {
  345. Connection.Tds.ExecuteQuery (BuildCommand (), CommandTimeout);
  346. }
  347. catch (TdsTimeoutException e) {
  348. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  349. }
  350. if (!Connection.Tds.NextResult () || !Connection.Tds.NextRow ())
  351. return null;
  352. object result = Connection.Tds.ColumnValues [0];
  353. CloseDataReader (true);
  354. return result;
  355. }
  356. public XmlReader ExecuteXmlReader ()
  357. {
  358. ValidateCommand ("ExecuteXmlReader");
  359. try {
  360. Connection.Tds.ExecuteQuery (BuildCommand (), CommandTimeout);
  361. }
  362. catch (TdsTimeoutException e) {
  363. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  364. }
  365. SqlDataReader dataReader = new SqlDataReader (this);
  366. SqlXmlTextReader textReader = new SqlXmlTextReader (dataReader);
  367. XmlReader xmlReader = new XmlTextReader (textReader);
  368. return xmlReader;
  369. }
  370. static string FormatParameter (SqlParameter parameter)
  371. {
  372. if (parameter.Value == null)
  373. return "NULL";
  374. switch (parameter.SqlDbType) {
  375. case SqlDbType.BigInt :
  376. case SqlDbType.Bit :
  377. case SqlDbType.Decimal :
  378. case SqlDbType.Float :
  379. case SqlDbType.Int :
  380. case SqlDbType.Money :
  381. case SqlDbType.Real :
  382. case SqlDbType.SmallInt :
  383. case SqlDbType.SmallMoney :
  384. case SqlDbType.TinyInt :
  385. return parameter.Value.ToString ();
  386. case SqlDbType.NVarChar :
  387. case SqlDbType.NChar :
  388. return String.Format ("N'{0}'", parameter.Value.ToString ().Replace ("'", "''"));
  389. default:
  390. return String.Format ("'{0}'", parameter.Value.ToString ().Replace ("'", "''"));
  391. }
  392. }
  393. private void GetOutputParameters ()
  394. {
  395. Connection.Tds.SkipToEnd ();
  396. IList list = Connection.Tds.ColumnValues;
  397. if (list != null && list.Count > 0) {
  398. int index = 0;
  399. foreach (SqlParameter parameter in parameters) {
  400. if (parameter.Direction != ParameterDirection.Input) {
  401. parameter.Value = list [index];
  402. index += 1;
  403. }
  404. if (index >= list.Count)
  405. break;
  406. }
  407. }
  408. }
  409. object ICloneable.Clone ()
  410. {
  411. return new SqlCommand (commandText, Connection);
  412. }
  413. IDbDataParameter IDbCommand.CreateParameter ()
  414. {
  415. return CreateParameter ();
  416. }
  417. IDataReader IDbCommand.ExecuteReader ()
  418. {
  419. return ExecuteReader ();
  420. }
  421. IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
  422. {
  423. return ExecuteReader (behavior);
  424. }
  425. void IDisposable.Dispose ()
  426. {
  427. Dispose (true);
  428. }
  429. public void Prepare ()
  430. {
  431. ValidateCommand ("Prepare");
  432. Connection.Tds.ExecuteNonQuery (BuildPrepare ());
  433. if (Connection.Tds.OutputParameters.Count == 0 || Connection.Tds.OutputParameters[0] == null)
  434. throw new Exception ("Could not prepare the statement.");
  435. preparedStatements [commandText] = ((int) Connection.Tds.OutputParameters [0]).ToString ();
  436. }
  437. public void ResetCommandTimeout ()
  438. {
  439. commandTimeout = 30;
  440. }
  441. private void ValidateCommand (string method)
  442. {
  443. if (Connection == null)
  444. throw new InvalidOperationException (String.Format ("{0} requires a Connection object to continue.", method));
  445. if (Connection.Transaction != null && transaction != Connection.Transaction)
  446. throw new InvalidOperationException ("The Connection object does not have the same transaction as the command object.");
  447. if (Connection.State != ConnectionState.Open)
  448. throw new InvalidOperationException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", method));
  449. if (commandText == String.Empty || commandText == null)
  450. throw new InvalidOperationException ("The command text for this Command has not been set.");
  451. if (Connection.DataReader != null)
  452. throw new InvalidOperationException ("There is already an open DataReader associated with this Connection which must be closed first.");
  453. if (Connection.XmlReader != null)
  454. throw new InvalidOperationException ("There is already an open XmlReader associated with this Connection which must be closed first.");
  455. }
  456. #endregion // Methods
  457. }
  458. }