SqlDataAdapterTest.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. //
  2. // SqlDataAdapterTest.cs - NUnit Test Cases for testing the
  3. // SqlDataAdapter 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. using Mono.Data;
  36. using System.Configuration;
  37. using NUnit.Framework;
  38. namespace MonoTests.System.Data.SqlClient
  39. {
  40. [TestFixture]
  41. [Category ("sqlserver")]
  42. public class SqlDataAdapterTest
  43. {
  44. SqlDataAdapter adapter = null;
  45. DataSet data = null ;
  46. string connectionString = ConnectionManager.Singleton.ConnectionString;
  47. SqlConnection conn = null;
  48. /**
  49. The below test will not run everytime, since the region id column is unique
  50. so change the regionid if you want the test to pass.
  51. **/
  52. /*
  53. [Test]
  54. public void UpdateTest () {
  55. conn = (SqlConnection) ConnectionManager.Singleton.Connection;
  56. try {
  57. ConnectionManager.Singleton.OpenConnection ();
  58. DataTable dt = new DataTable();
  59. SqlDataAdapter da = null;
  60. da = new SqlDataAdapter("Select * from employee", conn);
  61. //SqlCommandBuilder cb = new SqlCommandBuilder (da);
  62. da.Fill(dt);
  63. DataRow dr = dt.NewRow();
  64. dr ["id"] = 6002;
  65. dr ["fname"] = "boston";
  66. dr ["dob"] = DateTime.Now.Subtract (new TimeSpan (20*365, 0, 0, 0));
  67. dr ["doj"] = DateTime.Now;
  68. dt.Rows.Add(dr);
  69. da.Update(dt);
  70. } finally {
  71. DBHelper.ExecuteSimpleSP (conn, "sp_clean_employee_table");
  72. ConnectionManager.Singleton.CloseConnection ();
  73. }
  74. }
  75. private static void OnRowUpdatedTest (object sender, SqlRowUpdatedEventArgs e)
  76. {
  77. rowUpdated = true;
  78. }
  79. private static void OnRowUpdatingTest (object sender, SqlRowUpdatingEventArgs e)
  80. {
  81. rowUpdating = true;
  82. }
  83. private static bool rowUpdated = false;
  84. private static bool rowUpdating = false;
  85. [Test]
  86. public void RowUpdatedTest () {
  87. conn = (SqlConnection) ConnectionManager.Singleton.Connection;
  88. try {
  89. ConnectionManager.Singleton.OpenConnection ();
  90. DataTable dt = null;
  91. DataSet ds = new DataSet ();
  92. SqlDataAdapter da = null;
  93. da = new SqlDataAdapter("Select * from employee", conn);
  94. //SqlCommandBuilder cb = new SqlCommandBuilder (da);
  95. rowUpdated = false;
  96. rowUpdating = false;
  97. da.RowUpdated += new SqlRowUpdatedEventHandler (OnRowUpdatedTest);
  98. da.RowUpdating += new SqlRowUpdatingEventHandler (OnRowUpdatingTest);
  99. da.Fill (ds);
  100. dt = ds.Tables [0];
  101. dt.Rows[0][0] = 200;
  102. da.UpdateCommand = new SqlCommand ("Update employee set id = @id");
  103. da.Update (dt);
  104. dt.Rows[0][0] = 1;
  105. da.Update (dt);
  106. da.RowUpdated -= new SqlRowUpdatedEventHandler (OnRowUpdatedTest);
  107. da.RowUpdating -= new SqlRowUpdatingEventHandler (OnRowUpdatingTest);
  108. Assert.AreEqual (true, rowUpdated, "RowUpdated");
  109. Assert.AreEqual (true, rowUpdating, "RowUpdating");
  110. } finally {
  111. DBHelper.ExecuteSimpleSP (conn, "sp_clean_employee_table");
  112. ConnectionManager.Singleton.CloseConnection ();
  113. }
  114. }
  115. */
  116. /**
  117. This needs a errortable created as follows
  118. id uniqueidentifier,name char(10) , with values
  119. Guid name
  120. {A12...} NULL
  121. NULL bbbbbb
  122. **/
  123. [Test]
  124. public void NullGuidTest()
  125. {
  126. conn = (SqlConnection) ConnectionManager.Singleton.Connection;
  127. try {
  128. ConnectionManager.Singleton.OpenConnection ();
  129. DBHelper.ExecuteNonQuery (conn, "create table #tmp_guid_table ( " +
  130. " id uniqueidentifier default newid (), " +
  131. " name char (10))");
  132. DBHelper.ExecuteNonQuery (conn, "insert into #tmp_guid_table (name) values (null)");
  133. DBHelper.ExecuteNonQuery (conn, "insert into #tmp_guid_table (id, name) values (null, 'bbbb')");
  134. SqlDataAdapter da = new SqlDataAdapter("select * from #tmp_guid_table", conn);
  135. DataSet ds = new DataSet();
  136. da.Fill(ds);
  137. Assert.AreEqual (1, ds.Tables.Count, "#1");
  138. Assert.AreEqual (DBNull.Value, ds.Tables [0].Rows [1] ["id"], "#2");
  139. } finally {
  140. ConnectionManager.Singleton.CloseConnection ();
  141. }
  142. // the bug 68804 - is that the fill hangs!
  143. Assert.AreEqual("Done","Done");
  144. }
  145. [Test]
  146. public void DefaultConstructorTest ()
  147. {
  148. adapter = new SqlDataAdapter ();
  149. Assert.AreEqual (MissingMappingAction.Passthrough,
  150. adapter.MissingMappingAction,
  151. "#1 Missing Mapping acttion default to Passthrough");
  152. Assert.AreEqual (MissingSchemaAction.Add,
  153. adapter.MissingSchemaAction,
  154. "#2 Missing Schme action default to Add");
  155. }
  156. [Test]
  157. public void OverloadedConstructorsTest ()
  158. {
  159. SqlCommand selCmd = new SqlCommand ("Select * from numeric_family");
  160. adapter = new SqlDataAdapter (selCmd);
  161. Assert.AreEqual (MissingMappingAction.Passthrough,
  162. adapter.MissingMappingAction,
  163. "#1 Missing Mapping acttion default to Passthrough");
  164. Assert.AreEqual (MissingSchemaAction.Add,
  165. adapter.MissingSchemaAction,
  166. "#2 Missing Schme action default to Add");
  167. Assert.AreSame (selCmd, adapter.SelectCommand,
  168. "#3 Select Command shud be a ref to the arg passed");
  169. conn = new SqlConnection (connectionString);
  170. String selStr = "Select * from numeric_family";
  171. adapter = new SqlDataAdapter (selStr, conn);
  172. Assert.AreEqual (MissingMappingAction.Passthrough,
  173. adapter.MissingMappingAction,
  174. "#4 Missing Mapping acttion default to Passthrough");
  175. Assert.AreEqual (MissingSchemaAction.Add,
  176. adapter.MissingSchemaAction,
  177. "#5 Missing Schme action default to Add");
  178. Assert.AreSame (selStr, adapter.SelectCommand.CommandText,
  179. "#6 Select Command shud be a ref to the arg passed");
  180. Assert.AreSame (conn, adapter.SelectCommand.Connection,
  181. "#7 cmd.connection shud be t ref to connection obj");
  182. selStr = "Select * from numeric_family";
  183. adapter = new SqlDataAdapter (selStr, connectionString);
  184. Assert.AreEqual (MissingMappingAction.Passthrough,
  185. adapter.MissingMappingAction,
  186. "#8 Missing Mapping action shud default to Passthrough");
  187. Assert.AreEqual (MissingSchemaAction.Add,
  188. adapter.MissingSchemaAction,
  189. "#9 Missing Schema action shud default to Add");
  190. Assert.AreSame (selStr,
  191. adapter.SelectCommand.CommandText,
  192. "#10");
  193. Assert.AreEqual (connectionString,
  194. adapter.SelectCommand.Connection.ConnectionString,
  195. "#11 ");
  196. }
  197. [Test]
  198. public void Fill_Test_ConnState ()
  199. {
  200. //Check if Connection State is maintained correctly ..
  201. data = new DataSet ("test1");
  202. adapter = new SqlDataAdapter ("select id from numeric_family where id=1",
  203. connectionString);
  204. SqlCommand cmd = adapter.SelectCommand ;
  205. Assert.AreEqual (ConnectionState.Closed,
  206. cmd.Connection.State, "#1 Connection shud be in closed state");
  207. adapter.Fill (data);
  208. Assert.AreEqual (1, data.Tables.Count, "#2 One table shud be populated");
  209. Assert.AreEqual (ConnectionState.Closed, cmd.Connection.State,
  210. "#3 Connection shud be closed state");
  211. data = new DataSet ("test2");
  212. cmd.Connection.Open ();
  213. Assert.AreEqual (ConnectionState.Open, cmd.Connection.State,
  214. "#3 Connection shud be open");
  215. adapter.Fill (data);
  216. Assert.AreEqual (1, data.Tables.Count, "#4 One table shud be populated");
  217. Assert.AreEqual (ConnectionState.Open, cmd.Connection.State,
  218. "#5 Connection shud be open");
  219. cmd.Connection.Close ();
  220. // Test if connection is closed when exception occurs
  221. cmd.CommandText = "select id1 from numeric_family";
  222. try {
  223. adapter.Fill (data);
  224. } catch {
  225. if (cmd.Connection.State == ConnectionState.Open) {
  226. cmd.Connection.Close ();
  227. Assert.Fail ("# Connection Shud be Closed");
  228. }
  229. }
  230. }
  231. [Test]
  232. public void Fill_Test_Data ()
  233. {
  234. //Check if a table is created for each resultset
  235. String batchQuery = "Select id,type_bit,type_int from numeric_family;";
  236. batchQuery += "Select type_bit,type_bigint from numeric_family";
  237. adapter = new SqlDataAdapter (batchQuery, connectionString);
  238. data = new DataSet ("test1");
  239. adapter.Fill (data);
  240. Assert.AreEqual (2, data.Tables.Count,"#1 2 Table shud be created");
  241. //Check if Table and Col are named correctly for unnamed columns
  242. string query = "Select 10,20 from numeric_family;" ;
  243. query += "Select 10,20 from numeric_family";
  244. adapter = new SqlDataAdapter (query, connectionString);
  245. data = new DataSet ("test2");
  246. adapter.Fill (data);
  247. Assert.AreEqual (2, data.Tables.Count,
  248. "#2 2 Tables shud be created");
  249. Assert.AreEqual ("Table", data.Tables[0].TableName, "#3");
  250. Assert.AreEqual ("Table1", data.Tables[1].TableName, "#4");
  251. Assert.AreEqual ("Column1", data.Tables[0].Columns[0].ColumnName, "#5");
  252. Assert.AreEqual ("Column2", data.Tables[0].Columns[1].ColumnName, "#6");
  253. Assert.AreEqual ("Column1", data.Tables[1].Columns[0].ColumnName, "#7");
  254. Assert.AreEqual ("Column2", data.Tables[1].Columns[1].ColumnName, "#8");
  255. //Check if dup columns are named correctly
  256. query = "select A.id ,B.id , C.id from numeric_family A, ";
  257. query += "numeric_family B , numeric_family C";
  258. adapter = new SqlDataAdapter (query, connectionString);
  259. data = new DataSet ("test3");
  260. adapter.Fill (data);
  261. // NOTE msdotnet contradicts documented behavior
  262. // as per documentation the column names should be
  263. // id1,id2,id3 .. but msdotnet returns id,id1,id2
  264. Assert.AreEqual ("id", data.Tables[0].Columns[0].ColumnName,
  265. "#9 if colname is duplicated ,shud be col,col1,col2 etc");
  266. Assert.AreEqual ("id1", data.Tables[0].Columns[1].ColumnName,
  267. "#10 if colname is duplicated ,shud be col,col1,col2 etc");
  268. Assert.AreEqual ("id2", data.Tables[0].Columns[2].ColumnName,
  269. "#11 if colname is duplicated ,shud be col,col1,col2 etc");
  270. // Test if tables are created and named accordingly ,
  271. // but only for those queries returning result sets
  272. query = "update numeric_family set id=100 where id=50;";
  273. query += "select * from numeric_family";
  274. adapter = new SqlDataAdapter (query, connectionString);
  275. data = new DataSet ("test4");
  276. adapter.Fill (data);
  277. Assert.AreEqual (1 ,data.Tables.Count,
  278. "#12 Tables shud be named only for queries returning a resultset");
  279. Assert.AreEqual ("Table", data.Tables[0].TableName,
  280. "#13 The first resutlset shud have 'Table' as its name");
  281. // Test behavior with an outerjoin
  282. query = "select A.id,B.type_bit from numeric_family A LEFT OUTER JOIN ";
  283. query += "numeric_family B on A.id = B.type_bit";
  284. adapter = new SqlDataAdapter (query, connectionString);
  285. data = new DataSet ("test5");
  286. adapter.Fill (data);
  287. Assert.AreEqual (0, data.Tables[0].PrimaryKey.Length,
  288. "#14 Primary Key shudnt be set if an outer join is performed");
  289. Assert.AreEqual (0, data.Tables[0].Constraints.Count,
  290. "#15 Constraints shudnt be set if an outer join is performed");
  291. adapter = new SqlDataAdapter ("select id from numeric_family",
  292. connectionString);
  293. data = new DataSet ("test6");
  294. adapter.Fill (data, 1, 1, "numeric_family");
  295. Assert.AreEqual (1, data.Tables[0].Rows.Count, "#16");
  296. Assert.AreEqual (2, data.Tables[0].Rows[0][0], "#17");
  297. // only one test for DataTable.. DataSet tests covers others
  298. adapter = new SqlDataAdapter ("select id from numeric_family",
  299. connectionString);
  300. DataTable table = new DataTable ("table1");
  301. adapter.Fill (table);
  302. Assert.AreEqual (4, table.Rows.Count , "#18");
  303. }
  304. [Test]
  305. public void Fill_Test_PriKey ()
  306. {
  307. // Test if Primary Key & Constraints Collection is correct
  308. adapter = new SqlDataAdapter ("select id,type_bit from numeric_family",
  309. connectionString);
  310. adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
  311. data = new DataSet ("test1");
  312. adapter.Fill (data);
  313. Assert.AreEqual (1, data.Tables[0].PrimaryKey.Length,
  314. "#1 Primary Key shud be set");
  315. Assert.AreEqual (1, data.Tables[0].Constraints.Count,
  316. "#2 Constraints shud be set");
  317. Assert.AreEqual (4, data.Tables[0].Rows.Count,
  318. "#3 No Of Rows shud be 4");
  319. // Test if data is correctly merged
  320. adapter.Fill (data);
  321. Assert.AreEqual (4, data.Tables[0].Rows.Count,
  322. "#4 No of Row shud still be 4");
  323. // Test if rows are appended and not merged
  324. // when primary key is not returned in the result-set
  325. string query = "Select type_int,type_bigint from numeric_family";
  326. adapter.SelectCommand.CommandText = query;
  327. data = new DataSet ("test2");
  328. adapter.Fill (data);
  329. Assert.AreEqual (4, data.Tables[0].Rows.Count,
  330. "#5 No of Rows shud be 4");
  331. adapter.Fill (data);
  332. Assert.AreEqual (8, data.Tables[0].Rows.Count,
  333. "#6 No of Rows shud double now");
  334. }
  335. [Test]
  336. public void Fill_Test_Exceptions ()
  337. {
  338. adapter = new SqlDataAdapter ("select * from numeric_family",
  339. connectionString);
  340. data = new DataSet ("test1");
  341. try {
  342. adapter.Fill (data, -1, 0, "numeric_family");
  343. Assert.Fail ("#1 Exception shud be thrown:Incorrect Arguments");
  344. }catch (AssertionException e){
  345. throw e;
  346. }catch (Exception e){
  347. Assert.AreEqual (typeof(ArgumentException), e.GetType(),
  348. "#2 Incorrect Exception : " + e);
  349. }
  350. // conn is not closed due to a bug..
  351. // can be removed later
  352. adapter.SelectCommand.Connection.Close ();
  353. try {
  354. adapter.Fill (data , 0 , -1 , "numeric_family");
  355. Assert.Fail ("#3 Exception shud be thrown:Incorrect Arguments");
  356. }catch (AssertionException e){
  357. throw e;
  358. }catch (Exception e){
  359. Assert.AreEqual (typeof(ArgumentException), e.GetType(),
  360. "#4 Incorrect Exception : " + e);
  361. }
  362. // conn is curr not closed.. can be removed later
  363. adapter.SelectCommand.Connection.Close ();
  364. /*
  365. // NOTE msdotnet contradicts documented behavior
  366. // InvalidOperationException is expected if table is not valid
  367. try {
  368. adapter.Fill (data , 0 , 0 , "invalid_talbe_name");
  369. }catch (InvalidOperationException e) {
  370. ex= e;
  371. }catch (Exception e){
  372. Assert.Fail ("#5 Exception shud be thrown : incorrect arugments ");
  373. }
  374. Assert.IsNotNull (ex , "#6 Exception shud be thrown : incorrect args ");
  375. adapter.SelectCommand.Connection.Close (); // tmp .. can be removed once the bug if fixed
  376. ex=null;
  377. */
  378. try {
  379. adapter.Fill ( null , 0 , 0 , "numeric_family");
  380. Assert.Fail ( "#7 Exception shud be thrown : Invalid Dataset");
  381. }catch (AssertionException e){
  382. throw e ;
  383. }catch (ArgumentNullException) {
  384. }catch (Exception e) {
  385. Assert.AreEqual (typeof(SystemException), e.GetType(),
  386. "#8 Incorrect Exception : " + e);
  387. }
  388. // conn is currently not being closed..
  389. //need to be removed once behavior is fixed
  390. adapter.SelectCommand.Connection.Close ();
  391. adapter.SelectCommand.Connection = null;
  392. try {
  393. adapter.Fill (data);
  394. Assert.Fail ("#9 Exception shud be thrown : Invalid Connection");
  395. }catch (AssertionException e){
  396. throw e;
  397. }catch (Exception e){
  398. Assert.AreEqual (typeof(InvalidOperationException), e.GetType(),
  399. "#10 Incorrect Exception : " + e);
  400. }
  401. }
  402. bool FillErrorContinue = false;
  403. [Test]
  404. public void Fill_Test_FillErrorTest ()
  405. {
  406. string query = "select type_bigint from numeric_family where id=1 or id=4 ";
  407. DataSet ds = new DataSet ();
  408. DataTable table = ds.Tables.Add ("test");
  409. table.Columns.Add ("col", typeof (int));
  410. adapter = new SqlDataAdapter (query, connectionString);
  411. DataTableMapping mapping = adapter.TableMappings.Add ("numeric_family", "test");
  412. mapping.ColumnMappings.Add ("type_bigint", "col");
  413. int count = 0;
  414. try {
  415. count = adapter.Fill (ds, "numeric_family");
  416. Assert.Fail ("#1 Overflow exception must be thrown");
  417. }catch (Exception e) {
  418. Assert.AreEqual (typeof (OverflowException), e.GetType (), "#1a Expected exception is OverflowException");
  419. }
  420. Assert.AreEqual (0, ds.Tables [0].Rows.Count, "#2");
  421. Assert.AreEqual (0, count, "#3");
  422. adapter.FillError += new FillErrorEventHandler (ErrorHandler);
  423. FillErrorContinue = false;
  424. try {
  425. count = adapter.Fill (ds, "numeric_family");
  426. Assert.Fail ("#4 Overflow exception must be thrown");
  427. }catch (Exception e) {
  428. Assert.AreEqual (typeof (OverflowException), e.GetType (), "#4 Overflow exception must be thrown");
  429. }
  430. Assert.AreEqual (0, ds.Tables [0].Rows.Count, "#5");
  431. Assert.AreEqual (0, count, "#6");
  432. FillErrorContinue = true;
  433. count = adapter.Fill (ds, "numeric_family");
  434. // 1 row shud be filled
  435. Assert.AreEqual (1, ds.Tables [0].Rows.Count, "#7");
  436. Assert.AreEqual (1, count, "#8");
  437. }
  438. void ErrorHandler (object sender, FillErrorEventArgs args)
  439. {
  440. args.Continue = FillErrorContinue;
  441. }
  442. [Test]
  443. public void GetFillParametersTest ()
  444. {
  445. string query = "select id, type_bit from numeric_family where id > @param1";
  446. adapter = new SqlDataAdapter (query, connectionString);
  447. IDataParameter[] param = adapter.GetFillParameters ();
  448. Assert.AreEqual (0, param.Length, "#1 size shud be 0");
  449. SqlParameter param1 = new SqlParameter ();
  450. param1.ParameterName = "@param1";
  451. param1.Value = 2;
  452. adapter.SelectCommand.Parameters.Add (param1);
  453. param = adapter.GetFillParameters ();
  454. Assert.AreEqual (1, param.Length, "#2 count shud be 1");
  455. Assert.AreEqual (param1, param[0], "#3 Params shud be equal");
  456. }
  457. [Test]
  458. public void FillSchemaTest ()
  459. {
  460. string query = "";
  461. // Test if connection is closed if excepton occurs during fill schema
  462. query = "select * from invalid_table";
  463. adapter = new SqlDataAdapter (query, connectionString);
  464. data = new DataSet ("test");
  465. try {
  466. adapter.FillSchema (data , SchemaType.Source);
  467. }catch {
  468. if ( adapter.SelectCommand.Connection.State != ConnectionState.Closed)
  469. {
  470. Assert.Fail ("#0 Conn shud be closed if exception occurs");
  471. adapter.SelectCommand.Connection.Close();
  472. }
  473. }
  474. // Test Primary Key is set (since primary key column returned)
  475. query = "select id, type_int from numeric_family where id=1";
  476. adapter = new SqlDataAdapter (query, connectionString);
  477. data = new DataSet ("test1");
  478. adapter.FillSchema (data , SchemaType.Source);
  479. Assert.AreEqual (1, data.Tables[0].PrimaryKey.Length,
  480. "#1 Primary Key property must be set");
  481. // Test Primary Key is not set (since primary key column is returned)
  482. query = "select type_bit, type_int from numeric_family where id=1";
  483. adapter = new SqlDataAdapter (query, connectionString);
  484. data = new DataSet ("test2");
  485. adapter.FillSchema (data, SchemaType.Source);
  486. Assert.AreEqual (0, data.Tables[0].PrimaryKey.Length,
  487. "#2 Primary Key property should not be set");
  488. // Test multiple tables are created for a batch query
  489. query = "Select id ,type_bit from numeric_family;" ;
  490. query += "Select id,type_bit,type_int from numeric_family;";
  491. data = new DataSet ("test3");
  492. adapter = new SqlDataAdapter (query, connectionString);
  493. adapter.FillSchema (data , SchemaType.Source);
  494. Assert.AreEqual (2 , data.Tables.Count , "#3 A table shud be created for each Result Set");
  495. Assert.AreEqual (2 , data.Tables[0].Columns.Count , "#4 should have 2 columns");
  496. Assert.AreEqual (3 , data.Tables[1].Columns.Count , "#5 Should have 3 columns");
  497. // Test if table names and column names are filled correctly
  498. query = "select 10,20 from numeric_family;" ;
  499. query += "select 10,20 from numeric_family;";
  500. adapter = new SqlDataAdapter (query, connectionString);
  501. data = new DataSet ("test4");
  502. try {
  503. adapter.FillSchema (data , SchemaType.Source);
  504. }catch (Exception e){
  505. Assert.Fail ("#3 Unexpected Exception : " + e);
  506. }
  507. Assert.AreEqual ( "Table", data.Tables[0].TableName);
  508. Assert.AreEqual ( "Table1", data.Tables[1].TableName);
  509. Assert.AreEqual ( "Column1", data.Tables[0].Columns[0].ColumnName,
  510. "#6 Unnamed col shud be named as 'ColumnN'");
  511. Assert.AreEqual ( "Column2", data.Tables[0].Columns[1].ColumnName,
  512. "#7 Unnamed col shud be named as 'ColumnN'");
  513. Assert.AreEqual ( "Column1", data.Tables[1].Columns[0].ColumnName,
  514. "#8 Unnamed col shud be named as 'ColumnN'");
  515. Assert.AreEqual ( "Column2", data.Tables[1].Columns[1].ColumnName,
  516. "#9 Unnamed col shud be named as 'ColumnN'");
  517. Assert.AreEqual (ConnectionState.Closed, adapter.SelectCommand.Connection.State,
  518. "#10 Connection shud be closed");
  519. // Test if mapping works correctly
  520. // doesent work in both mono and msdotnet
  521. // gotto check if something is wrong
  522. /*
  523. query = "select id,type_bit from numeric_family";
  524. adapter = new SqlDataAdapter (query, connectionString);
  525. data = new DataSet ("test");
  526. DataTable table = data.Tables.Add ("numeric_family_1");
  527. table.Columns.Add ("id");
  528. table.Columns.Add ("type_bit");
  529. DataTableMapping map = adapter.TableMappings.Add("numeric_family_1",
  530. "numeric_family");
  531. map.ColumnMappings.Add ("id", "id_1");
  532. map.ColumnMappings.Add ("type_bit", "type_bit_1");
  533. adapter.FillSchema (data, SchemaType.Source, "numeric_family");
  534. foreach (DataTable tab in data.Tables){
  535. Console.WriteLine ("Table == {0}",tab.TableName);
  536. foreach (DataColumn col in tab.Columns)
  537. Console.WriteLine (" Col = {0} " , col.ColumnName);
  538. }
  539. */
  540. }
  541. [Test]
  542. public void MissingSchemaActionTest ()
  543. {
  544. adapter = new SqlDataAdapter (
  545. "select id,type_bit,type_int from numeric_family where id<=4",
  546. connectionString);
  547. data = new DataSet ();
  548. Assert.AreEqual (MissingSchemaAction.Add, adapter.MissingSchemaAction,
  549. "#1 Default Value");
  550. adapter.Fill (data);
  551. Assert.AreEqual (1, data.Tables.Count , "#1 One table shud be populated");
  552. Assert.AreEqual (3, data.Tables[0].Columns.Count, "#2 Missing cols are added");
  553. Assert.AreEqual (0, data.Tables[0].PrimaryKey.Length, "#3 Default Value");
  554. adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
  555. data.Reset();
  556. adapter.Fill (data);
  557. Assert.AreEqual (3, data.Tables[0].Columns.Count,
  558. "#4 Missing cols are added");
  559. Assert.AreEqual (1, data.Tables[0].PrimaryKey.Length, "#5 Default Value");
  560. adapter.MissingSchemaAction = MissingSchemaAction.Ignore ;
  561. data.Reset ();
  562. adapter.Fill (data);
  563. Assert.AreEqual (0, data.Tables.Count, "#6 Data shud be ignored");
  564. adapter.MissingSchemaAction = MissingSchemaAction.Error ;
  565. data.Reset();
  566. try {
  567. adapter.Fill (data);
  568. Assert.Fail ("#8 Exception shud be thrown: Schema Mismatch");
  569. }catch (AssertionException e) {
  570. throw e;
  571. }catch (Exception e){
  572. Assert.AreEqual (typeof(InvalidOperationException), e.GetType(),
  573. "#9 Incorrect Exception : "+e);
  574. }
  575. // Test for invalid MissingSchema Value
  576. try {
  577. adapter.MissingSchemaAction = (MissingSchemaAction)(-5000);
  578. Assert.Fail ("#10 Exception shud be thrown: Invalid Value");
  579. }catch (AssertionException e){
  580. throw e;
  581. }catch (Exception e){
  582. Assert.AreEqual (typeof(ArgumentException), e.GetType(),
  583. "#11 Incorrect Exception : " +e);
  584. }
  585. // Tests if Data is filled correctly if schema is defined
  586. // manually and MissingSchemaAction.Error is set
  587. adapter.MissingSchemaAction = MissingSchemaAction.Error;
  588. data.Reset();
  589. DataTable table = data.Tables.Add ("Table");
  590. table.Columns.Add ("id");
  591. table.Columns.Add ("type_bit");
  592. table.Columns.Add ("type_int");
  593. try {
  594. adapter.Fill (data);
  595. Assert.AreEqual (1, data.Tables.Count, "#12");
  596. Assert.AreEqual (4, data.Tables[0].Rows.Count, "#13");
  597. }catch (Exception e) {
  598. Assert.Fail ("#12 Unexpected Exception : " + e);
  599. }
  600. }
  601. [Test]
  602. public void MissingMappingActionTest ()
  603. {
  604. adapter = new SqlDataAdapter ("select id,type_bit from numeric_family where id=1",
  605. connectionString);
  606. data = new DataSet ();
  607. Assert.AreEqual (adapter.MissingMappingAction,
  608. MissingMappingAction.Passthrough,
  609. "#1 Default Value");
  610. adapter.Fill(data);
  611. Assert.AreEqual (1, data.Tables.Count,
  612. "#2 One Table shud be created");
  613. Assert.AreEqual (2, data.Tables[0].Columns.Count,
  614. "#3 Two Cols shud be created");
  615. adapter.MissingMappingAction = MissingMappingAction.Ignore;
  616. data.Reset ();
  617. adapter.Fill (data);
  618. Assert.AreEqual (0, data.Tables.Count, "#4 No table shud be created");
  619. adapter.MissingMappingAction = MissingMappingAction.Error;
  620. data.Reset ();
  621. try {
  622. adapter.Fill (data);
  623. Assert.Fail ("#5 Exception shud be thrown : Mapping is missing");
  624. }catch (AssertionException e){
  625. throw e;
  626. }catch (Exception e) {
  627. Assert.AreEqual (typeof(InvalidOperationException), e.GetType(),
  628. "#6 Incorrect Exception : " + e);
  629. }
  630. try {
  631. adapter.MissingMappingAction = (MissingMappingAction)(-5000);
  632. Assert.Fail ("#7 Exception shud be thrown : Invalid Value");
  633. }catch (AssertionException e){
  634. throw e;
  635. }catch (Exception e){
  636. Assert.AreEqual (typeof(ArgumentException), e.GetType(),
  637. "#8 Incorrect Exception : " +e);
  638. }
  639. // Test if mapping the column and table names works correctly
  640. adapter.MissingMappingAction = MissingMappingAction.Error;
  641. data.Reset ();
  642. DataTable table = data.Tables.Add ("numeric_family_1");
  643. table.Columns.Add ("id_1");
  644. table.Columns.Add ("type_bit_1");
  645. table.Columns.Add ("type_int_1");
  646. DataTableMapping tableMap = adapter.TableMappings.Add ("numeric_family",
  647. "numeric_family_1");
  648. tableMap.ColumnMappings.Add ("id", "id_1");
  649. tableMap.ColumnMappings.Add ("type_bit", "type_bit_1");
  650. tableMap.ColumnMappings.Add ("type_int", "type_int_1");
  651. adapter.Fill (data,"numeric_family");
  652. Assert.AreEqual (1, data.Tables.Count ,
  653. "#8 The DataTable shud be correctly mapped");
  654. Assert.AreEqual (3, data.Tables[0].Columns.Count,
  655. "#9 The DataColumns shud be corectly mapped");
  656. Assert.AreEqual (1, data.Tables[0].Rows.Count,
  657. "#10 Data shud be populated if mapping is correct");
  658. }
  659. // Test case for bug #76433
  660. [Test]
  661. public void FillSchema_ValuesTest()
  662. {
  663. SqlConnection conn = new SqlConnection(connectionString);
  664. using (conn) {
  665. conn.Open();
  666. IDbCommand command = conn.CreateCommand();
  667. // Create Temp Table
  668. String cmd = "Create Table #tmp_TestTable (" ;
  669. cmd += "Field1 DECIMAL (10) NOT NULL,";
  670. cmd += "Field2 DECIMAL(19))";
  671. command.CommandText = cmd;
  672. command.ExecuteNonQuery();
  673. DataSet dataSet = new DataSet();
  674. string selectString = "SELECT * FROM #tmp_TestTable";
  675. IDbDataAdapter dataAdapter = new SqlDataAdapter (
  676. selectString,conn);
  677. dataAdapter.FillSchema(dataSet, SchemaType.Mapped);
  678. Assert.AreEqual (1, dataSet.Tables.Count, "#1");
  679. //DataColumn col = dataSet.Tables[0].Columns[0];
  680. Assert.IsFalse (dataSet.Tables[0].Columns[0].AllowDBNull,"#2");
  681. Assert.IsTrue (dataSet.Tables[0].Columns[1].AllowDBNull,"#3");
  682. }
  683. }
  684. [Test]
  685. public void Fill_CheckSchema ()
  686. {
  687. SqlConnection conn = new SqlConnection(connectionString);
  688. using (conn) {
  689. conn.Open();
  690. IDbCommand command = conn.CreateCommand();
  691. // Create Temp Table
  692. String cmd = "Create Table #tmp_TestTable (" ;
  693. cmd += "id int primary key,";
  694. cmd += "field int not null)";
  695. command.CommandText = cmd;
  696. command.ExecuteNonQuery();
  697. DataSet dataSet = new DataSet();
  698. string selectString = "SELECT * from #tmp_TestTable";
  699. IDbDataAdapter dataAdapter = new SqlDataAdapter (
  700. selectString,conn);
  701. dataAdapter.Fill (dataSet);
  702. Assert.IsTrue (dataSet.Tables[0].Columns[1].AllowDBNull, "#1");
  703. Assert.AreEqual (0, dataSet.Tables[0].PrimaryKey.Length, "#2");
  704. dataSet.Reset ();
  705. dataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey ;
  706. dataAdapter.Fill (dataSet);
  707. Assert.IsFalse (dataSet.Tables[0].Columns[1].AllowDBNull, "#3");
  708. Assert.AreEqual (1, dataSet.Tables[0].PrimaryKey.Length, "#4");
  709. }
  710. }
  711. [Test]
  712. public void FillSchema_CheckSchema ()
  713. {
  714. SqlConnection conn = new SqlConnection(connectionString);
  715. using (conn) {
  716. conn.Open();
  717. IDbCommand command = conn.CreateCommand();
  718. // Create Temp Table
  719. String cmd = "Create Table #tmp_TestTable (" ;
  720. cmd += "id int primary key,";
  721. cmd += "field int not null)";
  722. command.CommandText = cmd;
  723. command.ExecuteNonQuery();
  724. DataSet dataSet = new DataSet();
  725. string selectString = "SELECT * from #tmp_TestTable";
  726. IDbDataAdapter dataAdapter = new SqlDataAdapter (
  727. selectString,conn);
  728. dataAdapter.FillSchema (dataSet, SchemaType.Mapped);
  729. Assert.IsFalse (dataSet.Tables[0].Columns[1].AllowDBNull, "#1");
  730. dataSet.Reset ();
  731. dataAdapter.MissingSchemaAction = MissingSchemaAction.Add;
  732. dataAdapter.FillSchema (dataSet, SchemaType.Mapped);
  733. Assert.IsFalse (dataSet.Tables[0].Columns[1].AllowDBNull, "#2");
  734. dataSet.Reset ();
  735. dataAdapter.MissingSchemaAction = MissingSchemaAction.Ignore;
  736. dataAdapter.FillSchema (dataSet, SchemaType.Mapped);
  737. Assert.AreEqual (0, dataSet.Tables.Count, "#3");
  738. dataSet.Reset ();
  739. dataAdapter.MissingSchemaAction = MissingSchemaAction.Error;
  740. try {
  741. dataAdapter.FillSchema (dataSet, SchemaType.Mapped);
  742. Assert.Fail ("#4 Error should be thrown");
  743. } catch (Exception e) {
  744. Assert.AreEqual (typeof (InvalidOperationException), e.GetType (),
  745. "#4 InvalidOperationException must be thrown");
  746. }
  747. }
  748. }
  749. [Test]
  750. public void CreateViewSSPITest ()
  751. {
  752. SqlConnection conn = new SqlConnection (ConfigurationSettings.AppSettings ["SSPIConnString"]);
  753. conn.Open ();
  754. string sql = "create view MONO_TEST_VIEW as select * from Numeric_family";
  755. SqlCommand dbcmd = new SqlCommand( sql, conn );
  756. dbcmd.ExecuteNonQuery();
  757. sql = "drop view MONO_TEST_VIEW";
  758. dbcmd = new SqlCommand( sql, conn );
  759. dbcmd.ExecuteNonQuery();
  760. conn.Close();
  761. }
  762. [Test]
  763. public void Fill_RelatedTables ()
  764. {
  765. SqlConnection conn = new SqlConnection(connectionString);
  766. using (conn) {
  767. conn.Open();
  768. IDbCommand command = conn.CreateCommand();
  769. DataSet dataSet = new DataSet();
  770. string selectString = "SELECT id, type_int from numeric_family where id < 3";
  771. DbDataAdapter dataAdapter = new SqlDataAdapter (selectString,conn);
  772. DataTable table2 = dataSet.Tables.Add ("table2");
  773. DataColumn ccol1 = table2.Columns.Add ("id", typeof (int));
  774. DataColumn ccol2 = table2.Columns.Add ("type_int", typeof (int));
  775. DataTable table1 = dataSet.Tables.Add ("table1");
  776. DataColumn pcol1 = table1.Columns.Add ("id", typeof (int));
  777. DataColumn pcol2 = table1.Columns.Add ("type_int", typeof (int));
  778. table2.Constraints.Add ("fk", pcol1, ccol1);
  779. //table1.Constraints.Add ("fk1", pcol2, ccol2);
  780. dataSet.EnforceConstraints = false;
  781. dataAdapter.Fill (dataSet, "table1");
  782. dataAdapter.Fill (dataSet, "table2");
  783. //Should not throw an exception
  784. dataSet.EnforceConstraints = true;
  785. Assert.AreEqual (2, table1.Rows.Count, "#1");
  786. Assert.AreEqual (2, table2.Rows.Count, "#2");
  787. }
  788. }
  789. #if NET_2_0
  790. [Test]
  791. public void UpdateBatchSizeTest ()
  792. {
  793. adapter = new SqlDataAdapter();
  794. Assert.AreEqual (1, adapter.UpdateBatchSize, "#1 The default value should be 1");
  795. adapter.UpdateBatchSize = 3;
  796. Assert.AreEqual (3, adapter.UpdateBatchSize, "#2 The value should be 3 after setting the property UpdateBatchSize to 3");
  797. }
  798. [Test]
  799. [ExpectedException (typeof (ArgumentOutOfRangeException))]
  800. public void UpdateBatchSizeArgumentOutOfRangeTest ()
  801. {
  802. adapter = new SqlDataAdapter();
  803. adapter.UpdateBatchSize = -2;
  804. }
  805. #endif
  806. }
  807. #if NET_2_0
  808. [TestFixture]
  809. [Category ("sqlserver")]
  810. public class SqlDataAdapterInheritTest : DbDataAdapter
  811. {
  812. SqlConnection conn = null;
  813. [Test]
  814. public void FillDataAdapterTest () {
  815. conn = (SqlConnection) ConnectionManager.Singleton.Connection;
  816. try {
  817. ConnectionManager.Singleton.OpenConnection ();
  818. DataTable dt = new DataTable();
  819. SqlCommand command = new SqlCommand ();
  820. command.CommandText = "Select * from employee;";
  821. command.Connection = conn;
  822. SelectCommand = command;
  823. Fill (dt, command.ExecuteReader ());
  824. Assert.AreEqual (6, dt.Rows.Count, "#1");
  825. Assert.AreEqual (6, dt.Columns.Count, "#1");
  826. } finally {
  827. DBHelper.ExecuteSimpleSP (conn, "sp_clean_employee_table");
  828. ConnectionManager.Singleton.CloseConnection ();
  829. }
  830. }
  831. }
  832. #endif
  833. }