SqlCommand.cs 16 KB

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