SqlCommand.cs 13 KB

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