SqlCommand.cs 15 KB

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