SqlCommandTest.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  1. //
  2. // SqlCommandTest.cs - NUnit Test Cases for testing the
  3. // SqlCommand class
  4. // Author:
  5. // Umadevi S ([email protected])
  6. // Sureshkumar T ([email protected])
  7. // Senganal T ([email protected])
  8. //
  9. // Copyright (c) 2004 Novell Inc., and the individuals listed
  10. // on the ChangeLog entries.
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System;
  32. using System.Data;
  33. using System.Data.Common;
  34. using System.Data.SqlClient;
  35. #if NET_2_0
  36. using System.Data.Sql;
  37. using System.Xml;
  38. #endif
  39. using NUnit.Framework;
  40. namespace MonoTests.System.Data.SqlClient
  41. {
  42. [TestFixture]
  43. [Category ("sqlserver")]
  44. public class SqlCommandTest
  45. {
  46. public SqlConnection conn = null ;
  47. SqlCommand cmd = null;
  48. string connectionString = ConnectionManager.Singleton.ConnectionString;
  49. [SetUp]
  50. public void Setup ()
  51. {
  52. }
  53. [TearDown]
  54. public void TearDown ()
  55. {
  56. if (conn != null)
  57. conn.Close ();
  58. }
  59. [Test]
  60. public void ConstructorTest ()
  61. {
  62. // Test Default Constructor
  63. cmd = new SqlCommand ();
  64. Assert.AreEqual (String.Empty, cmd.CommandText,
  65. "#1 Command Test should be empty");
  66. Assert.AreEqual (30, cmd.CommandTimeout,
  67. "#2 CommandTimeout should be 30");
  68. Assert.AreEqual (CommandType.Text, cmd.CommandType,
  69. "#3 CommandType should be text");
  70. Assert.IsNull (cmd.Connection, "#4 Connection Should be null");
  71. Assert.AreEqual (0, cmd.Parameters.Count,
  72. "#5 Parameter shud be empty");
  73. // Test Overloaded Constructor
  74. String cmdText = "select * from tbl1" ;
  75. cmd = new SqlCommand (cmdText);
  76. Assert.AreEqual (cmdText, cmd.CommandText,
  77. "#5 CommandText should be the same as passed");
  78. Assert.AreEqual (30, cmd.CommandTimeout,
  79. "#6 CommandTimeout should be 30");
  80. Assert.AreEqual (CommandType.Text, cmd.CommandType,
  81. "#7 CommandType should be text");
  82. Assert.IsNull (cmd.Connection , "#8 Connection Should be null");
  83. // Test Overloaded Constructor
  84. SqlConnection conn = new SqlConnection ();
  85. cmd = new SqlCommand (cmdText , conn);
  86. Assert.AreEqual (cmdText, cmd.CommandText,
  87. "#9 CommandText should be the same as passed");
  88. Assert.AreEqual (30, cmd.CommandTimeout,
  89. "#10 CommandTimeout should be 30");
  90. Assert.AreEqual (CommandType.Text, cmd.CommandType,
  91. "#11 CommandType should be text");
  92. Assert.AreSame (cmd.Connection, conn, "#12 Connection Should be same");
  93. // Test Overloaded Constructor
  94. SqlTransaction trans = null ;
  95. try {
  96. conn = new SqlConnection (connectionString);
  97. conn.Open ();
  98. trans = conn.BeginTransaction ();
  99. cmd = new SqlCommand (cmdText, conn, trans);
  100. Assert.AreEqual (cmdText, cmd.CommandText,
  101. "#9 CommandText should be the same as passed");
  102. Assert.AreEqual (30, cmd.CommandTimeout,
  103. "#10 CommandTimeout should be 30");
  104. Assert.AreEqual (CommandType.Text, cmd.CommandType,
  105. "#11 CommandType should be text");
  106. Assert.AreEqual (cmd.Connection, conn,
  107. "#12 Connection Should be null");
  108. Assert.AreEqual (cmd.Transaction, trans,
  109. "#13 Transaction Property should be set");
  110. // Test if parameters are reset to Default Values
  111. cmd = new SqlCommand ();
  112. Assert.AreEqual (String.Empty, cmd.CommandText,
  113. "#1 Command Test should be empty");
  114. Assert.AreEqual (30, cmd.CommandTimeout,
  115. "#2 CommandTimeout should be 30");
  116. Assert.AreEqual (CommandType.Text, cmd.CommandType,
  117. "#3 CommandType should be text");
  118. Assert.IsNull (cmd.Connection, "#4 Connection Should be null");
  119. }finally {
  120. trans.Rollback ();
  121. }
  122. }
  123. [Test]
  124. public void ExecuteScalarTest ()
  125. {
  126. conn = new SqlConnection (connectionString);
  127. cmd = new SqlCommand ("" , conn);
  128. cmd.CommandText = "Select count(*) from numeric_family where id<=4";
  129. //Check Exception is thrown when executed on a closed connection
  130. try {
  131. cmd.ExecuteScalar ();
  132. Assert.Fail ("#1 InvalidOperation Exception must be thrown");
  133. }catch (AssertionException e) {
  134. throw e;
  135. }catch (Exception e) {
  136. #if NET_2_0
  137. Assert.AreEqual (typeof (NullReferenceException), e.GetType (),
  138. "#2 Incorrect Exception : " + e.StackTrace);
  139. #else
  140. Assert.AreEqual (typeof (InvalidOperationException), e.GetType (),
  141. "#2 Incorrect Exception : " + e.StackTrace);
  142. #endif
  143. }
  144. // Check the Return value for a Correct Query
  145. object result = 0;
  146. conn.Open ();
  147. result = cmd.ExecuteScalar ();
  148. Assert.AreEqual (4, (int)result, "#3 Query Result returned is incorrect");
  149. cmd.CommandText = "select id , type_bit from numeric_family order by id asc" ;
  150. result = Convert.ToInt32 (cmd.ExecuteScalar ());
  151. Assert.AreEqual (1, result,
  152. "#4 ExecuteScalar Should return (1,1) the result set" );
  153. cmd.CommandText = "select id from numeric_family where id=-1";
  154. result = cmd.ExecuteScalar ();
  155. Assert.IsNull (result, "#5 Null should be returned if result set is empty");
  156. // Check SqlException is thrown for Invalid Query
  157. cmd.CommandText = "select count* from numeric_family";
  158. try {
  159. result = cmd.ExecuteScalar ();
  160. Assert.Fail ("#6 InCorrect Query should cause an SqlException");
  161. }catch (AssertionException e) {
  162. throw e;
  163. }catch (Exception e) {
  164. Assert.AreEqual (typeof(SqlException), e.GetType(),
  165. "#7 Incorrect Exception : " + e.StackTrace);
  166. }
  167. // Parameterized stored procedure calls
  168. int int_value = 20;
  169. string string_value = "output value changed";
  170. string return_value = "first column of first rowset";
  171. cmd.CommandText =
  172. "create procedure #tmp_executescalar_outparams "+
  173. " (@p1 int, @p2 int out, @p3 varchar(200) out) "+
  174. "as " +
  175. "select '" + return_value + "' as 'col1', @p1 as 'col2' "+
  176. "set @p2 = @p2 * 2 "+
  177. "set @p3 = N'" + string_value + "' "+
  178. "select 'second rowset' as 'col1', 2 as 'col2' "+
  179. "return 1";
  180. cmd.CommandType = CommandType.Text;
  181. cmd.ExecuteNonQuery ();
  182. cmd.CommandText = "#tmp_executescalar_outparams";
  183. cmd.CommandType = CommandType.StoredProcedure;
  184. SqlParameter p1 = new SqlParameter ();
  185. p1.ParameterName = "@p1";
  186. p1.Direction = ParameterDirection.Input;
  187. p1.DbType = DbType.Int32;
  188. p1.Value = int_value;
  189. cmd.Parameters.Add (p1);
  190. SqlParameter p2 = new SqlParameter ();
  191. p2.ParameterName = "@p2";
  192. p2.Direction = ParameterDirection.InputOutput;
  193. p2.DbType = DbType.Int32;
  194. p2.Value = int_value;
  195. cmd.Parameters.Add (p2);
  196. SqlParameter p3 = new SqlParameter ();
  197. p3.ParameterName = "@p3";
  198. p3.Direction = ParameterDirection.Output;
  199. p3.DbType = DbType.String;
  200. p3.Size = 200;
  201. cmd.Parameters.Add (p3);
  202. result = cmd.ExecuteScalar ();
  203. Assert.AreEqual (return_value, result, "#8 ExecuteScalar Should return 'first column of first rowset'");
  204. Assert.AreEqual (int_value * 2, p2.Value, "#9 ExecuteScalar should fill the parameter collection with the outputted values");
  205. Assert.AreEqual (string_value, p3.Value, "#10 ExecuteScalar should fill the parameter collection with the outputted values");
  206. p3.Size = 0;
  207. p3.Value = null;
  208. try {
  209. cmd.ExecuteScalar ();
  210. Assert.Fail ("#11 Query should throw System.InvalidOperationException due to size = 0 and value = null");
  211. }
  212. catch (AssertionException e) {
  213. throw e;
  214. }
  215. catch (Exception e) {
  216. Assert.AreEqual (typeof (InvalidOperationException), e.GetType (),
  217. "#12 Incorrect Exception : " + e.StackTrace);
  218. }
  219. conn.Close ();
  220. }
  221. [Test]
  222. public void ExecuteNonQuery ()
  223. {
  224. conn = new SqlConnection (connectionString);
  225. cmd = new SqlCommand ("", conn);
  226. int result = 0;
  227. // Test for exceptions
  228. // Test exception is thrown if connection is closed
  229. cmd.CommandText = "Select id from numeric_family where id=1";
  230. try {
  231. cmd.ExecuteNonQuery ();
  232. Assert.Fail ("#1 Connextion shud be open");
  233. }catch (AssertionException e) {
  234. throw e;
  235. }catch (Exception e) {
  236. #if NET_2_0
  237. Assert.AreEqual (typeof(NullReferenceException), e.GetType(),
  238. "#2 Incorrect Exception : " + e);
  239. #else
  240. Assert.AreEqual (typeof(InvalidOperationException), e.GetType(),
  241. "#2 Incorrect Exception : " + e);
  242. #endif
  243. }
  244. // Test Exception is thrown if Query is incorrect
  245. conn.Open ();
  246. cmd.CommandText = "Select id1 from numeric_family";
  247. try {
  248. cmd.ExecuteNonQuery ();
  249. Assert.Fail ("#1 invalid Query");
  250. }catch (AssertionException e) {
  251. throw e;
  252. }catch (Exception e) {
  253. Assert.AreEqual (typeof(SqlException), e.GetType(),
  254. "#2 Incorrect Exception : " + e);
  255. }
  256. // Test Select/Insert/Update/Delete Statements
  257. SqlTransaction trans = conn.BeginTransaction ();
  258. cmd.Transaction = trans;
  259. try {
  260. cmd.CommandText = "Select id from numeric_family where id=1";
  261. result = cmd.ExecuteNonQuery ();
  262. Assert.AreEqual (-1, result, "#1");
  263. cmd.CommandText = "Insert into numeric_family (id,type_int) values (100,200)";
  264. result = cmd.ExecuteNonQuery ();
  265. Assert.AreEqual (1, result, "#2 One row shud be inserted");
  266. cmd.CommandText = "Update numeric_family set type_int=300 where id=100";
  267. result = cmd.ExecuteNonQuery ();
  268. Assert.AreEqual (1, result, "#3 One row shud be updated");
  269. // Test Batch Commands
  270. cmd.CommandText = "Select id from numeric_family where id=1;";
  271. cmd.CommandText += "update numeric_family set type_int=10 where id=1000";
  272. cmd.CommandText += "update numeric_family set type_int=10 where id=100";
  273. result = cmd.ExecuteNonQuery ();
  274. Assert.AreEqual (1, result, "#4 One row shud be updated");
  275. cmd.CommandText = "Delete from numeric_family where id=100";
  276. result = cmd.ExecuteNonQuery ();
  277. Assert.AreEqual (1, result, "#5 One row shud be deleted");
  278. }finally {
  279. trans.Rollback ();
  280. }
  281. // Parameterized stored procedure calls
  282. int int_value = 20;
  283. string string_value = "output value changed";
  284. cmd.CommandText =
  285. "create procedure #tmp_executescalar_outparams " +
  286. " (@p1 int, @p2 int out, @p3 varchar(200) out) " +
  287. "as " +
  288. "select 'test' as 'col1', @p1 as 'col2' " +
  289. "set @p2 = @p2 * 2 " +
  290. "set @p3 = N'" + string_value + "' " +
  291. "select 'second rowset' as 'col1', 2 as 'col2' " +
  292. "return 1";
  293. cmd.CommandType = CommandType.Text;
  294. cmd.ExecuteNonQuery ();
  295. cmd.CommandText = "#tmp_executescalar_outparams";
  296. cmd.CommandType = CommandType.StoredProcedure;
  297. SqlParameter p1 = new SqlParameter ();
  298. p1.ParameterName = "@p1";
  299. p1.Direction = ParameterDirection.Input;
  300. p1.DbType = DbType.Int32;
  301. p1.Value = int_value;
  302. cmd.Parameters.Add (p1);
  303. SqlParameter p2 = new SqlParameter ();
  304. p2.ParameterName = "@p2";
  305. p2.Direction = ParameterDirection.InputOutput;
  306. p2.DbType = DbType.Int32;
  307. p2.Value = int_value;
  308. cmd.Parameters.Add (p2);
  309. SqlParameter p3 = new SqlParameter ();
  310. p3.ParameterName = "@p3";
  311. p3.Direction = ParameterDirection.Output;
  312. p3.DbType = DbType.String;
  313. p3.Size = 200;
  314. cmd.Parameters.Add (p3);
  315. cmd.ExecuteNonQuery ();
  316. Assert.AreEqual (int_value * 2, p2.Value, "#6 ExecuteNonQuery should fill the parameter collection with the outputted values");
  317. Assert.AreEqual (string_value, p3.Value, "#7 ExecuteNonQuery should fill the parameter collection with the outputted values");
  318. }
  319. [Test]
  320. public void ExecuteReaderTest ()
  321. {
  322. SqlDataReader reader = null;
  323. conn = new SqlConnection (connectionString);
  324. // Test exception is thrown if conn is closed
  325. cmd = new SqlCommand ("Select count(*) from numeric_family");
  326. try {
  327. reader = cmd.ExecuteReader ();
  328. }catch (AssertionException e) {
  329. throw e;
  330. }catch (Exception e) {
  331. #if NET_2_0
  332. Assert.AreEqual (typeof(NullReferenceException), e.GetType(),
  333. "#1 Incorrect Exception");
  334. #else
  335. Assert.AreEqual (typeof(InvalidOperationException), e.GetType(),
  336. "#1 Incorrect Exception");
  337. #endif
  338. }
  339. conn.Open ();
  340. // Test exception is thrown for Invalid Query
  341. cmd = new SqlCommand ("InvalidQuery", conn);
  342. try {
  343. reader = cmd.ExecuteReader ();
  344. Assert.Fail ("#1 Exception shud be thrown");
  345. }catch (AssertionException e) {
  346. throw e;
  347. }catch (Exception e) {
  348. Assert.AreEqual (typeof(SqlException), e.GetType (),
  349. "#2 Incorrect Exception : " + e);
  350. }
  351. // NOTE
  352. // Test SqlException is thrown if a row is locked
  353. // should lock a particular row and then modify it
  354. /*
  355. */
  356. // Test Connection cannot be modified when reader is in use
  357. // NOTE : msdotnet contradicts documented behavior
  358. cmd.CommandText = "select * from numeric_family where id=1";
  359. reader = cmd.ExecuteReader ();
  360. reader.Read ();
  361. conn.Close (); // valid operation
  362. conn = new SqlConnection (connectionString);
  363. /*
  364. // NOTE msdotnet contradcits documented behavior
  365. // If the above testcase fails, then this shud be tested
  366. // Test connection can be modified once reader is closed
  367. conn.Close ();
  368. reader.Close ();
  369. conn = new SqlConnection (connectionString); // valid operation
  370. */
  371. }
  372. [Test]
  373. public void ExecuteReaderCommandBehaviorTest ()
  374. {
  375. // Test for command behaviors
  376. DataTable schemaTable = null;
  377. SqlDataReader reader = null;
  378. conn = new SqlConnection (connectionString);
  379. conn.Open ();
  380. cmd = new SqlCommand ("", conn);
  381. cmd.CommandText = "Select id from numeric_family where id <=4 order by id asc;";
  382. cmd.CommandText += "Select type_bit from numeric_family where id <=4 order by id asc";
  383. // Test for default command behavior
  384. reader = cmd.ExecuteReader ();
  385. int rows = 0;
  386. int results = 0;
  387. do {
  388. while (reader.Read ())
  389. rows++ ;
  390. Assert.AreEqual (4, rows, "#1 Multiple rows shud be returned");
  391. results++;
  392. rows = 0;
  393. }while (reader.NextResult());
  394. Assert.AreEqual (2, results, "#2 Multiple result sets shud be returned");
  395. reader.Close ();
  396. // Test if closing reader, closes the connection
  397. reader = cmd.ExecuteReader (CommandBehavior.CloseConnection);
  398. reader.Close ();
  399. Assert.AreEqual (ConnectionState.Closed, conn.State,
  400. "#3 Command Behavior is not followed");
  401. conn.Open();
  402. // Test if row info and primary Key info is returned
  403. reader = cmd.ExecuteReader (CommandBehavior.KeyInfo);
  404. schemaTable = reader.GetSchemaTable ();
  405. Assert.IsTrue(reader.HasRows, "#4 Data Rows shud also be returned");
  406. Assert.IsTrue ((bool)schemaTable.Rows[0]["IsKey"],
  407. "#5 Primary Key info shud be returned");
  408. reader.Close ();
  409. // Test only column information is returned
  410. reader = cmd.ExecuteReader (CommandBehavior.SchemaOnly);
  411. schemaTable = reader.GetSchemaTable ();
  412. Assert.IsFalse (reader.HasRows, "#6 row data shud not be returned");
  413. Assert.AreEqual(DBNull.Value, schemaTable.Rows[0]["IsKey"],
  414. "#7 Primary Key info shud not be returned");
  415. Assert.AreEqual ("id", schemaTable.Rows[0]["ColumnName"],
  416. "#8 Schema Data is Incorrect");
  417. reader.Close ();
  418. // Test only one result set (first) is returned
  419. reader = cmd.ExecuteReader (CommandBehavior.SingleResult);
  420. schemaTable = reader.GetSchemaTable ();
  421. Assert.IsFalse (reader.NextResult(),
  422. "#9 Only one result set shud be returned");
  423. Assert.AreEqual ("id", schemaTable.Rows[0]["ColumnName"],
  424. "#10 The result set returned shud be the first result set");
  425. reader.Close ();
  426. // Test only one row is returned for all result sets
  427. // msdotnet doesnt work correctly.. returns only one result set
  428. reader = cmd.ExecuteReader (CommandBehavior.SingleRow);
  429. rows=0;
  430. results=0;
  431. do {
  432. while (reader.Read ())
  433. rows++ ;
  434. Assert.AreEqual (1, rows, "#11 Only one row shud be returned");
  435. results++;
  436. rows = 0;
  437. }while (reader.NextResult());
  438. // NOTE msdotnet contradicts documented behavior.
  439. // Multiple result sets shud be returned , and in this case : 2
  440. //Assert.AreEqual (2, results, "# Multiple result sets shud be returned");
  441. Assert.AreEqual (2, results, "#12 Multiple result sets shud be returned");
  442. reader.Close ();
  443. }
  444. [Test]
  445. public void PrepareTest_CheckValidStatement ()
  446. {
  447. cmd = new SqlCommand ();
  448. conn = new SqlConnection (connectionString);
  449. conn.Open ();
  450. cmd.CommandText = "Select id from numeric_family where id=@ID" ;
  451. cmd.Connection = conn ;
  452. // Test if Parameters are correctly populated
  453. cmd.Parameters.Clear ();
  454. cmd.Parameters.Add ("@ID", SqlDbType.TinyInt);
  455. cmd.Parameters["@ID"].Value = 2 ;
  456. cmd.Prepare ();
  457. Assert.AreEqual (2, cmd.ExecuteScalar (), "#3 Prepared Stmt not working");
  458. cmd.Parameters[0].Value = 3;
  459. Assert.AreEqual (3, cmd.ExecuteScalar (), "#4 Prep Stmt not working");
  460. conn.Close ();
  461. }
  462. [Test]
  463. public void PrepareTest ()
  464. {
  465. cmd = new SqlCommand ();
  466. conn = new SqlConnection (connectionString);
  467. conn.Open ();
  468. cmd.CommandText = "Select id from numeric_family where id=@ID" ;
  469. cmd.Connection = conn ;
  470. // Test InvalidOperation Exception is thrown if Parameter Type
  471. // is not explicitly set
  472. cmd.Parameters.Add ("@ID", 2);
  473. try {
  474. cmd.Prepare ();
  475. Assert.Fail ("#1 Parameter Type shud be explicitly Set");
  476. }catch (AssertionException e) {
  477. throw e;
  478. }catch (Exception e) {
  479. Assert.AreEqual (typeof(InvalidOperationException), e.GetType (),
  480. "#2 Incorrect Exception : " + e.StackTrace);
  481. }
  482. // Test Exception is thrown for variable size data if precision/scale
  483. // is not set
  484. cmd.CommandText = "select type_varchar from string_family where type_varchar=@p1";
  485. cmd.Parameters.Clear ();
  486. cmd.Parameters.Add ("@p1", SqlDbType.VarChar);
  487. cmd.Parameters["@p1"].Value = "afasasadadada";
  488. try {
  489. cmd.Prepare ();
  490. Assert.Fail ("#5 Exception shud be thrown");
  491. }catch (AssertionException e) {
  492. throw e;
  493. }catch (Exception e) {
  494. Assert.AreEqual (typeof(InvalidOperationException), e.GetType(),
  495. "#6 Incorrect Exception " + e.StackTrace);
  496. }
  497. // Test Exception is not thrown for Stored Procs
  498. try {
  499. cmd.CommandType = CommandType.StoredProcedure;
  500. cmd.CommandText = "ABFSDSFSF" ;
  501. cmd.Prepare ();
  502. }catch (Exception e) {
  503. Assert.Fail ("#7 Exception shud not be thrown for Stored Procs");
  504. }
  505. cmd.CommandType = CommandType.Text;
  506. conn.Close ();
  507. //Test InvalidOperation Exception is thrown if connection is not set
  508. cmd.Connection = null;
  509. try {
  510. cmd.Prepare ();
  511. #if NET_2_0
  512. Assert.Fail ("#8 NullReferenceException should be thrown");
  513. #else
  514. Assert.Fail ("#8 InvalidOperation Exception should be thrown");
  515. #endif
  516. }
  517. catch (AssertionException e) {
  518. throw e;
  519. }catch (Exception e) {
  520. #if NET_2_0
  521. Assert.AreEqual (typeof (NullReferenceException), e.GetType (),
  522. "#9 Incorrect Exception : " + e.StackTrace);
  523. #else
  524. Assert.AreEqual (typeof (InvalidOperationException), e.GetType (),
  525. "#9 Incorrect Exception : " + e.StackTrace);
  526. #endif
  527. }
  528. //Test InvalidOperation Exception is thrown if connection is closed
  529. cmd.Connection = conn ;
  530. try{
  531. cmd.Prepare ();
  532. Assert.Fail ("#4 InvalidOperation Exception shud be thrown");
  533. }catch (AssertionException e) {
  534. throw e;
  535. }catch (Exception e) {
  536. #if NET_2_0
  537. Assert.AreEqual (typeof(NullReferenceException), e.GetType(),
  538. "Incorrect Exception : " + e.StackTrace);
  539. #else
  540. Assert.AreEqual (typeof(InvalidOperationException), e.GetType(),
  541. "Incorrect Exception : " + e.StackTrace);
  542. #endif
  543. }
  544. }
  545. [Test]
  546. public void ResetTimeOut ()
  547. {
  548. SqlCommand cmd = new SqlCommand ();
  549. cmd.CommandTimeout = 50 ;
  550. Assert.AreEqual ( cmd.CommandTimeout, 50,
  551. "#1 CommandTimeout should be modfiable");
  552. cmd.ResetCommandTimeout ();
  553. Assert.AreEqual (cmd.CommandTimeout, 30,
  554. "#2 Reset Should set the Timeout to default value");
  555. }
  556. [Test]
  557. [ExpectedException (typeof(ArgumentException))]
  558. public void CommandTimeout ()
  559. {
  560. cmd = new SqlCommand ();
  561. cmd.CommandTimeout = 10;
  562. Assert.AreEqual (10, cmd.CommandTimeout, "#1");
  563. cmd.CommandTimeout = -1;
  564. }
  565. [Test]
  566. #if NET_2_0
  567. [ExpectedException (typeof(ArgumentOutOfRangeException))]
  568. #else
  569. [ExpectedException (typeof(ArgumentException))]
  570. #endif
  571. public void CommandTypeTest ()
  572. {
  573. cmd = new SqlCommand ();
  574. Assert.AreEqual (CommandType.Text ,cmd.CommandType,
  575. "Default CommandType is text");
  576. cmd.CommandType = (CommandType)(-1);
  577. }
  578. [Test]
  579. [Ignore ("msdotnet contradicts documented behavior")]
  580. [ExpectedException (typeof(InvalidOperationException))]
  581. public void ConnectionTest ()
  582. {
  583. SqlTransaction trans = null;
  584. try {
  585. conn = new SqlConnection (connectionString);
  586. conn.Open ();
  587. trans = conn.BeginTransaction ();
  588. cmd = new SqlCommand ("", conn,trans);
  589. cmd.CommandText = "Select id from numeric_family where id=1";
  590. cmd.Connection = new SqlConnection ();
  591. }finally {
  592. trans.Rollback();
  593. conn.Close ();
  594. }
  595. }
  596. [Test]
  597. public void TransactionTest ()
  598. {
  599. conn = new SqlConnection (connectionString);
  600. cmd = new SqlCommand ("", conn);
  601. Assert.IsNull (cmd.Transaction, "#1 Default value is null");
  602. SqlConnection conn1 = new SqlConnection (connectionString);
  603. conn1.Open ();
  604. SqlTransaction trans1 = conn1.BeginTransaction ();
  605. cmd.Transaction = trans1 ;
  606. try {
  607. cmd.ExecuteNonQuery ();
  608. Assert.Fail ("#2 Connection cannot be different");
  609. }catch (Exception e) {
  610. #if NET_2_0
  611. Assert.AreEqual (typeof(NullReferenceException), e.GetType(),
  612. "#3 Incorrect Exception : " + e);
  613. #else
  614. Assert.AreEqual (typeof(InvalidOperationException), e.GetType(),
  615. "#3 Incorrect Exception : " + e);
  616. #endif
  617. }finally {
  618. conn1.Close ();
  619. conn.Close ();
  620. }
  621. }
  622. // Need to add more tests
  623. [Test]
  624. #if NET_2_0
  625. [ExpectedException (typeof(ArgumentOutOfRangeException))]
  626. #else
  627. [ExpectedException (typeof(ArgumentException))]
  628. #endif
  629. public void UpdatedRowSourceTest ()
  630. {
  631. cmd = new SqlCommand ();
  632. Assert.AreEqual (UpdateRowSource.Both, cmd.UpdatedRowSource,
  633. "#1 Default value is both");
  634. cmd.UpdatedRowSource = UpdateRowSource.None;
  635. Assert.AreEqual (UpdateRowSource.None, cmd.UpdatedRowSource,
  636. "#2");
  637. cmd.UpdatedRowSource = (UpdateRowSource) (-1);
  638. }
  639. [Test]
  640. public void ExecuteNonQueryTempProcedureTest () {
  641. conn = (SqlConnection) ConnectionManager.Singleton.Connection;
  642. try {
  643. ConnectionManager.Singleton.OpenConnection ();
  644. // create temp sp here, should normally be created in Setup of test
  645. // case, but cannot be done right now because of ug #68978
  646. DBHelper.ExecuteNonQuery (conn, CREATE_TMP_SP_TEMP_INSERT_PERSON);
  647. SqlCommand cmd = new SqlCommand();
  648. cmd.Connection = conn;
  649. cmd.CommandText = "#sp_temp_insert_employee";
  650. cmd.CommandType = CommandType.StoredProcedure;
  651. Object TestPar = "test";
  652. cmd.Parameters.Add("@fname", SqlDbType.VarChar);
  653. cmd.Parameters ["@fname"].Value = TestPar;
  654. Assert.AreEqual(1,cmd.ExecuteNonQuery());
  655. } finally {
  656. DBHelper.ExecuteNonQuery (conn, DROP_TMP_SP_TEMP_INSERT_PERSON);
  657. DBHelper.ExecuteSimpleSP (conn, "sp_clean_person_table");
  658. ConnectionManager.Singleton.CloseConnection ();
  659. }
  660. }
  661. // Test for bug #76778
  662. // Test for a case, when query size is greater than the block size
  663. [Test]
  664. public void LongQueryTest ()
  665. {
  666. SqlConnection conn = new SqlConnection (
  667. connectionString + ";Pooling=false");
  668. using (conn) {
  669. conn.Open ();
  670. SqlCommand cmd = conn.CreateCommand ();
  671. String value = new String ('a', 10000);
  672. cmd.CommandText = String.Format ("Select '{0}'", value);
  673. cmd.ExecuteNonQuery ();
  674. }
  675. }
  676. // Test for bug #76778
  677. // To make sure RPC (when implemented) works ok..
  678. [Test]
  679. public void LongStoredProcTest()
  680. {
  681. SqlConnection conn = new SqlConnection (
  682. connectionString + ";Pooling=false");
  683. using (conn) {
  684. conn.Open ();
  685. int size = conn.PacketSize ;
  686. SqlCommand cmd = conn.CreateCommand ();
  687. // create a temp stored proc ..
  688. cmd.CommandText = "Create Procedure #sp_tmp_long_params ";
  689. cmd.CommandText += "@p1 nvarchar (4000), ";
  690. cmd.CommandText += "@p2 nvarchar (4000), ";
  691. cmd.CommandText += "@p3 nvarchar (4000), ";
  692. cmd.CommandText += "@p4 nvarchar (4000) out ";
  693. cmd.CommandText += "As ";
  694. cmd.CommandText += "Begin ";
  695. cmd.CommandText += "Set @p4 = N'Hello' ";
  696. cmd.CommandText += "Return 2 ";
  697. cmd.CommandText += "End";
  698. cmd.ExecuteNonQuery ();
  699. //execute the proc
  700. cmd.CommandType = CommandType.StoredProcedure;
  701. cmd.CommandText = "#sp_tmp_long_params";
  702. String value = new String ('a', 4000);
  703. SqlParameter p1 = new SqlParameter ("@p1",
  704. SqlDbType.NVarChar,4000);
  705. p1.Value = value;
  706. SqlParameter p2 = new SqlParameter ("@p2",
  707. SqlDbType.NVarChar,4000);
  708. p2.Value = value;
  709. SqlParameter p3 = new SqlParameter ("@p3",
  710. SqlDbType.NVarChar,4000);
  711. p3.Value = value;
  712. SqlParameter p4 = new SqlParameter ("@p4",
  713. SqlDbType.NVarChar,4000);
  714. p4.Direction = ParameterDirection.Output;
  715. // for now, name shud be @RETURN_VALUE
  716. // can be changed once RPC is implemented
  717. SqlParameter p5 = new SqlParameter ("@RETURN_VALUE", SqlDbType.Int);
  718. p5.Direction = ParameterDirection.ReturnValue ;
  719. cmd.Parameters.Add (p1);
  720. cmd.Parameters.Add (p2);
  721. cmd.Parameters.Add (p3);
  722. cmd.Parameters.Add (p4);
  723. cmd.Parameters.Add (p5);
  724. cmd.ExecuteNonQuery ();
  725. Assert.AreEqual ("Hello", p4.Value, "#1");
  726. Assert.AreEqual (2, p5.Value, "#2");
  727. }
  728. }
  729. // Test for bug #76880
  730. [Test]
  731. public void DateTimeParameterTest ()
  732. {
  733. SqlConnection conn = new SqlConnection (connectionString);
  734. using (conn) {
  735. conn.Open ();
  736. SqlCommand cmd = conn.CreateCommand ();
  737. cmd.CommandText = "select * from datetime_family where type_datetime=@p1";
  738. cmd.Parameters.Add ("@p1", SqlDbType.DateTime).Value= "10-10-2005";
  739. // shudnt cause and exception
  740. SqlDataReader rdr = cmd.ExecuteReader ();
  741. rdr.Close ();
  742. }
  743. }
  744. /**
  745. * Verifies whether an enum value is converted to a numeric value when
  746. * used as value for a numeric parameter (bug #66630)
  747. */
  748. [Test]
  749. public void EnumParameterTest() {
  750. conn = (SqlConnection) ConnectionManager.Singleton.Connection;
  751. try {
  752. ConnectionManager.Singleton.OpenConnection ();
  753. // create temp sp here, should normally be created in Setup of test
  754. // case, but cannot be done right now because of ug #68978
  755. DBHelper.ExecuteNonQuery (conn, "CREATE PROCEDURE #Bug66630 ("
  756. + "@Status smallint = 7"
  757. + ")"
  758. + "AS" + Environment.NewLine
  759. + "BEGIN" + Environment.NewLine
  760. + "SELECT CAST(5 AS int), @Status" + Environment.NewLine
  761. + "END");
  762. SqlCommand cmd = new SqlCommand("#Bug66630", conn);
  763. cmd.CommandType = CommandType.StoredProcedure;
  764. cmd.Parameters.Add("@Status", SqlDbType.Int).Value = Status.Error;
  765. using (SqlDataReader dr = cmd.ExecuteReader()) {
  766. // one record should be returned
  767. Assert.IsTrue(dr.Read(), "EnumParameterTest#1");
  768. // we should get two field in the result
  769. Assert.AreEqual(2, dr.FieldCount, "EnumParameterTest#2");
  770. // field 1
  771. Assert.AreEqual("int", dr.GetDataTypeName(0), "EnumParameterTest#3");
  772. Assert.AreEqual(5, dr.GetInt32(0), "EnumParameterTest#4");
  773. // field 2
  774. Assert.AreEqual("smallint", dr.GetDataTypeName(1), "EnumParameterTest#5");
  775. Assert.AreEqual((short) Status.Error, dr.GetInt16(1), "EnumParameterTest#6");
  776. // only one record should be returned
  777. Assert.IsFalse(dr.Read(), "EnumParameterTest#7");
  778. }
  779. } finally {
  780. DBHelper.ExecuteNonQuery (conn, "if exists (select name from sysobjects " +
  781. " where name like '#temp_Bug66630' and type like 'P') " +
  782. " drop procedure #temp_Bug66630; ");
  783. ConnectionManager.Singleton.CloseConnection ();
  784. }
  785. }
  786. /**
  787. * The below test does not need a connection but since the setup opens
  788. * the connection i will need to close it
  789. */
  790. [Test]
  791. public void CloneTest() {
  792. ConnectionManager.Singleton.OpenConnection ();
  793. SqlCommand cmd = new SqlCommand();
  794. cmd.Connection = null;
  795. cmd.CommandText = "sp_insert";
  796. cmd.CommandType = CommandType.StoredProcedure;
  797. Object TestPar = DBNull.Value;
  798. cmd.Parameters.Add("@TestPar1", SqlDbType.Int);
  799. cmd.Parameters["@TestPar1"].Value = TestPar;
  800. cmd.Parameters.Add("@BirthDate", DateTime.Now);
  801. cmd.DesignTimeVisible = true;
  802. cmd.CommandTimeout = 100;
  803. Object clone1 = ((ICloneable)(cmd)).Clone();
  804. SqlCommand cmd1 = (SqlCommand) clone1;
  805. Assert.AreEqual(2, cmd1.Parameters.Count);
  806. Assert.AreEqual(100, cmd1.CommandTimeout);
  807. cmd1.Parameters.Add("@test", DateTime.Now);
  808. // to check that it is deep copy and not a shallow copy of the
  809. // parameter collection
  810. Assert.AreEqual(3, cmd1.Parameters.Count);
  811. Assert.AreEqual(2, cmd.Parameters.Count);
  812. }
  813. [Test]
  814. [ExpectedException (typeof (InvalidOperationException))]
  815. public void OutputParamSizeTest1 ()
  816. {
  817. conn = (SqlConnection) ConnectionManager.Singleton.Connection;
  818. ConnectionManager.Singleton.OpenConnection ();
  819. cmd = new SqlCommand ();
  820. cmd.Connection = conn;
  821. cmd.CommandText = "create procedure #testsize (@p1 as varchar(10) output) as return";
  822. cmd.CommandType = CommandType.Text;
  823. cmd.ExecuteNonQuery ();
  824. cmd.CommandText = "#testsize";
  825. cmd.CommandType = CommandType.StoredProcedure;
  826. SqlParameter p1 = new SqlParameter ();
  827. p1.ParameterName = "@p1";
  828. p1.Direction = ParameterDirection.InputOutput;
  829. p1.DbType = DbType.String;
  830. p1.IsNullable = false;
  831. cmd.Parameters.Add (p1);
  832. cmd.ExecuteNonQuery ();
  833. }
  834. [Test]
  835. [ExpectedException (typeof (InvalidOperationException))]
  836. public void OutputParamSizeTest2 ()
  837. {
  838. conn = (SqlConnection) ConnectionManager.Singleton.Connection;
  839. ConnectionManager.Singleton.OpenConnection ();
  840. cmd = new SqlCommand ();
  841. cmd.Connection = conn;
  842. cmd.CommandText = "create procedure #testsize (@p1 as varchar(10) output) as return";
  843. cmd.CommandType = CommandType.Text;
  844. cmd.ExecuteNonQuery ();
  845. cmd.CommandText = "#testsize";
  846. cmd.CommandType = CommandType.StoredProcedure;
  847. SqlParameter p1 = new SqlParameter ();
  848. p1.ParameterName = "@p1";
  849. p1.Direction = ParameterDirection.Output;
  850. p1.DbType = DbType.String;
  851. p1.IsNullable = false;
  852. cmd.Parameters.Add (p1);
  853. cmd.ExecuteNonQuery ();
  854. }
  855. [Test]
  856. [ExpectedException (typeof (InvalidOperationException))]
  857. public void OutputParamSizeTest3 ()
  858. {
  859. conn = (SqlConnection) ConnectionManager.Singleton.Connection;
  860. ConnectionManager.Singleton.OpenConnection ();
  861. cmd = new SqlCommand ();
  862. cmd.Connection = conn;
  863. cmd.CommandText = "create procedure #testsize (@p1 as varchar(10) output) as return";
  864. cmd.CommandType = CommandType.Text;
  865. cmd.ExecuteNonQuery ();
  866. cmd.CommandText = "#testsize";
  867. cmd.CommandType = CommandType.StoredProcedure;
  868. SqlParameter p1 = new SqlParameter ();
  869. p1.ParameterName = "@p1";
  870. p1.Direction = ParameterDirection.InputOutput;
  871. p1.DbType = DbType.String;
  872. p1.IsNullable = true;
  873. cmd.Parameters.Add (p1);
  874. cmd.ExecuteNonQuery ();
  875. }
  876. [Test]
  877. [ExpectedException (typeof (InvalidOperationException))]
  878. public void OutputParamSizeTest4 ()
  879. {
  880. conn = (SqlConnection) ConnectionManager.Singleton.Connection;
  881. ConnectionManager.Singleton.OpenConnection ();
  882. cmd = new SqlCommand ();
  883. cmd.Connection = conn;
  884. cmd.CommandText = "create procedure #testsize (@p1 as varchar(10) output) as return";
  885. cmd.CommandType = CommandType.Text;
  886. cmd.ExecuteNonQuery ();
  887. cmd.CommandText = "#testsize";
  888. cmd.CommandType = CommandType.StoredProcedure;
  889. SqlParameter p1 = new SqlParameter ();
  890. p1.ParameterName = "@p1";
  891. p1.Direction = ParameterDirection.Output;
  892. p1.DbType = DbType.String;
  893. p1.IsNullable = true;
  894. cmd.Parameters.Add (p1);
  895. cmd.ExecuteNonQuery ();
  896. }
  897. #if NET_2_0
  898. [Test]
  899. public void NotificationTest ()
  900. {
  901. cmd = new SqlCommand ();
  902. SqlNotificationRequest notification = new SqlNotificationRequest("MyNotification","MyService",15);
  903. Assert.AreEqual (null, cmd.Notification, "#1 The default value for this property should be null");
  904. cmd.Notification = notification;
  905. Assert.AreEqual ("MyService", cmd.Notification.Options, "#2 The value should be MyService as the constructor is initiated with this value");
  906. Assert.AreEqual (15, cmd.Notification.Timeout, "#2 The value should be 15 as the constructor is initiated with this value");
  907. }
  908. [Test]
  909. public void NotificationAutoEnlistTest ()
  910. {
  911. cmd = new SqlCommand ();
  912. Assert.AreEqual (true, cmd.NotificationAutoEnlist, "#1 Default value of the property should be true");
  913. cmd.NotificationAutoEnlist = false;
  914. Assert.AreEqual (false, cmd.NotificationAutoEnlist, "#2 The value of the property should be false after setting it to false");
  915. }
  916. [Test]
  917. public void BeginExecuteXmlReaderTest ()
  918. {
  919. cmd = new SqlCommand ();
  920. string connectionString1 = null;
  921. connectionString1 = ConnectionManager.Singleton.ConnectionString + "Asynchronous Processing=true";
  922. try {
  923. SqlConnection conn1 = new SqlConnection (connectionString1);
  924. conn1.Open ();
  925. cmd.CommandText = "Select lname from employee where id<2 FOR XML AUTO, XMLDATA" ;
  926. cmd.Connection = conn1;
  927. IAsyncResult result = cmd.BeginExecuteXmlReader ();
  928. XmlReader reader = cmd.EndExecuteXmlReader (result);
  929. while (reader.Read ())
  930. {
  931. if (reader.LocalName.ToString () == "employee")
  932. {
  933. Assert.AreEqual ("kumar", reader["lname"], "#1 ");
  934. }
  935. }
  936. } finally {
  937. ConnectionManager.Singleton.CloseConnection ();
  938. }
  939. }
  940. [Test]
  941. public void BeginExecuteXmlReaderExceptionTest ()
  942. {
  943. cmd = new SqlCommand ();
  944. try {
  945. SqlConnection conn = new SqlConnection (connectionString);
  946. conn.Open ();
  947. cmd.CommandText = "Select lname from employee where id<2 FOR XML AUTO, XMLDATA" ;
  948. cmd.Connection = conn;
  949. try {
  950. IAsyncResult result = cmd.BeginExecuteXmlReader ();
  951. } catch (InvalidOperationException) {
  952. Assert.AreEqual (ConnectionManager.Singleton.ConnectionString, connectionString, "#1 Connection string has changed");
  953. return;
  954. }
  955. Assert.Fail ("Expected Exception InvalidOperationException not thrown");
  956. } finally {
  957. ConnectionManager.Singleton.CloseConnection ();
  958. }
  959. }
  960. [Test]
  961. public void CloneObjTest ()
  962. {
  963. SqlCommand cmd = new SqlCommand();
  964. cmd.CommandText = "sp_insert";
  965. cmd.CommandType = CommandType.StoredProcedure;
  966. Object TestPar = DBNull.Value;
  967. cmd.Parameters.Add ("@TestPar1", SqlDbType.Int);
  968. cmd.Parameters ["@TestPar1"].Value = TestPar;
  969. cmd.Parameters.Add ("@BirthDate", DateTime.Now);
  970. cmd.DesignTimeVisible = true;
  971. cmd.CommandTimeout = 100;
  972. SqlCommand cmd1 = cmd.Clone ();
  973. Assert.AreEqual (2, cmd1.Parameters.Count);
  974. Assert.AreEqual (100, cmd1.CommandTimeout);
  975. cmd1.Parameters.Add ("@test", DateTime.Now);
  976. Assert.AreEqual (3, cmd1.Parameters.Count);
  977. Assert.AreEqual (2, cmd.Parameters.Count);
  978. }
  979. #endif
  980. private enum Status {
  981. OK = 0,
  982. Error = 3
  983. }
  984. private readonly string CREATE_TMP_SP_TEMP_INSERT_PERSON = ("create procedure #sp_temp_insert_employee ( " + Environment.NewLine +
  985. "@fname varchar (20)) " + Environment.NewLine +
  986. "as " + Environment.NewLine +
  987. "begin" + Environment.NewLine +
  988. "declare @id int;" + Environment.NewLine +
  989. "select @id = max (id) from employee;" + Environment.NewLine +
  990. "set @id = @id + 6000 + 1;" + Environment.NewLine +
  991. "insert into employee (id, fname, dob, doj) values (@id, @fname, '1980-02-11', getdate ());" + Environment.NewLine +
  992. "return @id;" + Environment.NewLine +
  993. "end");
  994. private readonly string DROP_TMP_SP_TEMP_INSERT_PERSON = ("if exists (select name from sysobjects where " + Environment.NewLine +
  995. "name = '#sp_temp_insert_employee' and type = 'P') " + Environment.NewLine +
  996. "drop procedure #sp_temp_insert_employee; ");
  997. }
  998. }