SqlCommand.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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.Specialized;
  16. using System.ComponentModel;
  17. using System.Data;
  18. using System.Data.Common;
  19. using System.Runtime.InteropServices;
  20. using System.Text;
  21. using System.Xml;
  22. namespace System.Data.SqlClient {
  23. public sealed class SqlCommand : Component, IDbCommand, ICloneable
  24. {
  25. #region Fields
  26. int commandTimeout;
  27. bool designTimeVisible;
  28. string commandText;
  29. CommandType commandType;
  30. SqlConnection connection;
  31. SqlTransaction transaction;
  32. SqlParameterCollection parameters = new SqlParameterCollection ();
  33. private CommandBehavior behavior = CommandBehavior.Default;
  34. NameValueCollection procedureCache = new NameValueCollection ();
  35. #endregion // Fields
  36. #region Constructors
  37. public SqlCommand()
  38. : this (String.Empty, null, null)
  39. {
  40. }
  41. public SqlCommand (string commandText)
  42. : this (commandText, null, null)
  43. {
  44. commandText = commandText;
  45. }
  46. public SqlCommand (string commandText, SqlConnection connection)
  47. : this (commandText, connection, null)
  48. {
  49. Connection = connection;
  50. }
  51. public SqlCommand (string commandText, SqlConnection connection, SqlTransaction transaction)
  52. {
  53. this.commandText = commandText;
  54. this.connection = connection;
  55. this.transaction = transaction;
  56. this.commandType = CommandType.Text;
  57. this.designTimeVisible = false;
  58. this.commandTimeout = 30;
  59. }
  60. #endregion // Constructors
  61. #region Properties
  62. internal CommandBehavior CommandBehavior {
  63. get { return behavior; }
  64. }
  65. public string CommandText {
  66. get { return CommandText; }
  67. set { commandText = value; }
  68. }
  69. public int CommandTimeout {
  70. get { return commandTimeout; }
  71. set {
  72. if (commandTimeout < 0)
  73. throw new ArgumentException ("The property value assigned is less than 0.");
  74. commandTimeout = value;
  75. }
  76. }
  77. public CommandType CommandType {
  78. get { return commandType; }
  79. [MonoTODO ("Validate")]
  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. public void Cancel ()
  132. {
  133. if (connection == null || connection.Tds == null)
  134. return;
  135. connection.Tds.Cancel ();
  136. connection.CheckForErrors ();
  137. }
  138. internal void CloseDataReader (bool moreResults)
  139. {
  140. while (moreResults)
  141. moreResults = connection.Tds.NextResult ();
  142. if (connection.Tds.OutputParameters.Count > 0) {
  143. int index = 0;
  144. foreach (SqlParameter parameter in parameters) {
  145. if (parameter.Direction != ParameterDirection.Input)
  146. parameter.Value = connection.Tds.OutputParameters[index];
  147. index += 1;
  148. if (index >= connection.Tds.OutputParameters.Count)
  149. break;
  150. }
  151. }
  152. connection.DataReaderOpen = false;
  153. if ((behavior & CommandBehavior.CloseConnection) != 0)
  154. connection.Close ();
  155. }
  156. public SqlParameter CreateParameter ()
  157. {
  158. return new SqlParameter ();
  159. }
  160. public int ExecuteNonQuery ()
  161. {
  162. int result = connection.Tds.ExecuteNonQuery (ValidateQuery ("ExecuteNonQuery"));
  163. connection.CheckForErrors ();
  164. return result;
  165. }
  166. public SqlDataReader ExecuteReader ()
  167. {
  168. return ExecuteReader (CommandBehavior.Default);
  169. }
  170. public SqlDataReader ExecuteReader (CommandBehavior behavior)
  171. {
  172. this.behavior = behavior;
  173. connection.Tds.ExecuteQuery (ValidateQuery ("ExecuteReader"));
  174. connection.CheckForErrors ();
  175. connection.DataReaderOpen = true;
  176. return new SqlDataReader (this);
  177. }
  178. public object ExecuteScalar ()
  179. {
  180. connection.Tds.ExecuteQuery (ValidateQuery ("ExecuteScalar"));
  181. bool moreResults = connection.Tds.NextResult ();
  182. connection.CheckForErrors ();
  183. if (!moreResults)
  184. return null;
  185. moreResults = connection.Tds.NextRow ();
  186. connection.CheckForErrors ();
  187. if (!moreResults)
  188. return null;
  189. object result = connection.Tds.ColumnValues[0];
  190. CloseDataReader (true);
  191. return result;
  192. }
  193. public XmlReader ExecuteXmlReader ()
  194. {
  195. connection.Tds.ExecuteQuery (ValidateQuery ("ExecuteXmlReader"));
  196. connection.CheckForErrors ();
  197. connection.DataReaderOpen = true;
  198. SqlDataReader dataReader = new SqlDataReader (this);
  199. SqlXmlTextReader textReader = new SqlXmlTextReader (dataReader);
  200. XmlReader xmlReader = new XmlTextReader (textReader);
  201. return xmlReader;
  202. }
  203. static string FormatParameter (SqlParameter parameter)
  204. {
  205. if (parameter.Value == null)
  206. return "NULL";
  207. switch (parameter.SqlDbType) {
  208. case SqlDbType.BigInt :
  209. case SqlDbType.Bit :
  210. case SqlDbType.Decimal :
  211. case SqlDbType.Float :
  212. case SqlDbType.Int :
  213. case SqlDbType.Money :
  214. case SqlDbType.Real :
  215. case SqlDbType.SmallInt :
  216. case SqlDbType.SmallMoney :
  217. case SqlDbType.TinyInt :
  218. return parameter.Value.ToString ();
  219. default:
  220. return String.Format ("'{0}'", parameter.Value.ToString ().Replace ("'", "''"));
  221. }
  222. }
  223. static string FormatQuery (string commandText, CommandType commandType, SqlParameterCollection parameters)
  224. {
  225. StringBuilder result = new StringBuilder ();
  226. switch (commandType) {
  227. case CommandType.Text :
  228. return commandText;
  229. case CommandType.TableDirect :
  230. return String.Format ("SELECT * FROM {0}", commandText);
  231. case CommandType.StoredProcedure :
  232. StringBuilder parms = new StringBuilder ();
  233. StringBuilder declarations = new StringBuilder ();
  234. foreach (SqlParameter parameter in parameters) {
  235. switch (parameter.Direction) {
  236. case ParameterDirection.Input :
  237. if (parms.Length > 0)
  238. result.Append (",");
  239. parms.Append (FormatParameter (parameter));
  240. break;
  241. case ParameterDirection.Output :
  242. if (parms.Length > 0)
  243. parms.Append (",");
  244. parms.Append (parameter.ParameterName);
  245. parms.Append (" OUT");
  246. if (declarations.Length == 0)
  247. declarations.Append ("DECLARE ");
  248. else
  249. declarations.Append (",");
  250. declarations.Append (parameter.Prepare ());
  251. break;
  252. default :
  253. throw new NotImplementedException ("Only support input and output parameters.");
  254. }
  255. }
  256. result.Append (declarations.ToString ());
  257. result.Append (" EXEC ");
  258. result.Append (commandText);
  259. result.Append (" ");
  260. result.Append (parms);
  261. return result.ToString ();
  262. default:
  263. throw new InvalidOperationException ("The CommandType was not recognized.");
  264. }
  265. }
  266. [MonoTODO]
  267. object ICloneable.Clone ()
  268. {
  269. throw new NotImplementedException ();
  270. }
  271. IDbDataParameter IDbCommand.CreateParameter ()
  272. {
  273. return CreateParameter ();
  274. }
  275. IDataReader IDbCommand.ExecuteReader ()
  276. {
  277. return ExecuteReader ();
  278. }
  279. IDataReader IDbCommand.ExecuteReader (CommandBehavior behavior)
  280. {
  281. return ExecuteReader (behavior);
  282. }
  283. void IDisposable.Dispose ()
  284. {
  285. Dispose (true);
  286. }
  287. public void Prepare ()
  288. {
  289. bool prependComma = false;
  290. Guid uniqueId = Guid.NewGuid ();
  291. string procedureName = String.Format ("#mono#{0}", uniqueId.ToString ("N"));
  292. StringBuilder procedureString = new StringBuilder ();
  293. procedureString.Append ("CREATE PROC ");
  294. procedureString.Append (procedureName);
  295. procedureString.Append (" (");
  296. foreach (SqlParameter parameter in parameters) {
  297. if (prependComma)
  298. procedureString.Append (", ");
  299. else
  300. prependComma = true;
  301. procedureString.Append (parameter.Prepare ());
  302. if (parameter.Direction == ParameterDirection.Output)
  303. procedureString.Append (" OUT");
  304. }
  305. procedureString.Append (") AS ");
  306. procedureString.Append (commandText);
  307. string cmdText = FormatQuery (procedureName, CommandType.StoredProcedure, parameters);
  308. connection.Tds.ExecuteNonQuery (procedureString.ToString ());
  309. procedureCache[commandText] = cmdText;
  310. }
  311. public void ResetCommandTimeout ()
  312. {
  313. commandTimeout = 30;
  314. }
  315. string ValidateQuery (string methodName)
  316. {
  317. if (connection == null)
  318. throw new InvalidOperationException (String.Format ("{0} requires a Connection object to continue.", methodName));
  319. if (connection.Transaction != null && transaction != connection.Transaction)
  320. throw new InvalidOperationException ("The Connection object does not have the same transaction as the command object.");
  321. if (connection.State != ConnectionState.Open)
  322. throw new InvalidOperationException (String.Format ("ExecuteNonQuery requires an open Connection object to continue. This connection is closed.", methodName));
  323. if (commandText == String.Empty || commandText == null)
  324. throw new InvalidOperationException ("The command text for this Command has not been set.");
  325. string sql = procedureCache[commandText];
  326. if (sql == null)
  327. sql = FormatQuery (commandText, commandType, parameters);
  328. if ((behavior & CommandBehavior.KeyInfo) != 0)
  329. sql += " FOR BROWSE";
  330. return sql;
  331. }
  332. #endregion // Methods
  333. }
  334. }