PageRenderTime 796ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/Tests/Mite.Core.IntegrationTests/MsSql/MsSqlAdapterTestFixture.cs

http://mite-net.googlecode.com/
C# | 502 lines | 363 code | 111 blank | 28 comment | 1 complexity | 4e348b72fab3388a84cdcecfdb9c32bd MD5 | raw file
Possible License(s): LGPL-3.0, LGPL-2.1, BSD-3-Clause, Apache-2.0
  1. /***************************************************COPYRIGHT***************************************
  2. * Copyright (c) 2008, Whiteboard-IT
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that
  6. * the following conditions are met:
  7. *
  8. * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
  9. * disclaimer.
  10. *
  11. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
  12. * disclaimer in the documentation and/or other materials provided with the distribution.
  13. *
  14. * Neither the name of Whiteboard-IT, LLC nor the names of its contributors may be used to endorse or promote
  15. * products derived from this software without specific prior written permission.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  18. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  19. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  20. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  21. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  22. * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  23. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24. *****************************************************************************************************************/
  25. using System;
  26. using System.Collections.Generic;
  27. using System.Data;
  28. using System.Data.SqlClient;
  29. using System.Linq;
  30. using Boo.Lang;
  31. using MbUnit.Framework;
  32. using Mite.Configuration;
  33. using Mite.MsSql;
  34. namespace Mite.Core.Tests.Integration
  35. {
  36. [Author("Nathan")]
  37. [TestCategory("MsSql Integration")]
  38. [TestFixture]
  39. public class MsSqlAdapterTestFixture : MsSqlIntegrationTestBase
  40. {
  41. [SetUp]
  42. public void SetUp()
  43. {
  44. Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
  45. using (var conn = IoC.Resolve<IDbConnection>())
  46. {
  47. conn.Open();
  48. MsSqlUtility.CleanDatabase(conn, testDatabase.Name);
  49. conn.Close();
  50. }
  51. }
  52. [Test]
  53. public void CreateTable()
  54. {
  55. const string tableName = "some_table";
  56. using (IDbConnection conn = GetConnection())
  57. {
  58. conn.Open();
  59. MsSqlAdapter dao = GetMsSqlAdapter();
  60. IDbCommand cmd = dao.CreateTable(conn, new Table(tableName, GetIdColumn()));
  61. cmd.ExecuteNonQuery();
  62. }
  63. AssertTableExists(tableName);
  64. }
  65. [Test]
  66. public void DropTable()
  67. {
  68. const string tableName = "some_table";
  69. var table = new Table(tableName, GetIdColumn());
  70. MsSqlAdapter adapter = GetMsSqlAdapter();
  71. using (IDbConnection conn = GetConnection(adapter))
  72. {
  73. conn.Open();
  74. IDbCommand cmd = adapter.CreateTable(conn, table);
  75. cmd.ExecuteNonQuery();
  76. AssertTableExists(tableName);
  77. IDbCommand dropCommand = adapter.DropTable(conn, table);
  78. dropCommand.ExecuteNonQuery();
  79. AssertTableDoesNotExist(tableName);
  80. conn.Close();
  81. }
  82. }
  83. [Test]
  84. public void CreateSchemaTable()
  85. {
  86. using (IDbConnection conn = GetConnection())
  87. {
  88. conn.Open();
  89. MsSqlAdapter dao = GetMsSqlAdapter();
  90. IDbCommand[] cmds = dao.CreateSchemaTable(conn, testDatabase);
  91. cmds.ForEach(cmd => { cmd.ExecuteNonQuery(); });
  92. }
  93. AssertTableExists(Adapter.MIGRATION_SCHEMA_TABLE_NAME);
  94. }
  95. [Test]
  96. public void RenameTable()
  97. {
  98. const string newName = "new_name";
  99. Table table = GetTable();
  100. string originalName = table.Name;
  101. MsSqlAdapter adapter = GetMsSqlAdapter();
  102. using (IDbConnection conn = GetConnection(adapter))
  103. {
  104. conn.Open();
  105. IDbCommand createCommand = adapter.CreateTable(conn, table);
  106. createCommand.ExecuteNonQuery();
  107. AssertTableExists(originalName);
  108. IDbCommand renameCommand = adapter.RenameTable(conn, table, newName);
  109. renameCommand.ExecuteNonQuery();
  110. AssertTableDoesNotExist(originalName);
  111. AssertTableExists(newName);
  112. conn.Close();
  113. }
  114. }
  115. [Test]
  116. public void AlterColumn()
  117. {
  118. const string columnName = "some_column";
  119. Column originalColumn = new NVarCharColumn(columnName, 200);
  120. Column newColumn = new NVarCharColumn(columnName, 255)
  121. {
  122. IsNullable = true
  123. };
  124. Table table = GetTable(originalColumn);
  125. newColumn.Table = table;
  126. MsSqlAdapter adapter = GetMsSqlAdapter();
  127. using (IDbConnection conn = GetConnection(adapter))
  128. {
  129. conn.Open();
  130. IDbCommand createCommand = adapter.CreateTable(conn, table);
  131. createCommand.ExecuteNonQuery();
  132. IDbCommand alterCommand = adapter.AlterColumn(conn, originalColumn, newColumn);
  133. alterCommand.ExecuteNonQuery();
  134. conn.Close();
  135. }
  136. }
  137. [Test]
  138. public void AlterTable_AddColumn()
  139. {
  140. CreateAlterMeTable();
  141. var addedColumn = new Column("added_column", DbType.Decimal);
  142. addedColumn.Table = new Table("alter_me", addedColumn);
  143. // TODO: This shouldn't be checked by the dao, but right now this is how it's done.
  144. MsSqlAdapter dao = GetMsSqlAdapter();
  145. using (IDbConnection conn = GetConnection())
  146. {
  147. conn.Open();
  148. IDbCommand cmd = dao.AddColumnToTable(conn, new Table("alter_me"), addedColumn);
  149. cmd.ExecuteNonQuery();
  150. Database db = dao.GetDatabase(conn, testDatabase.Name);
  151. Table tbl = db.Tables.Single(t => t.Name.Equals("alter_me"));
  152. Assert.IsTrue(tbl.Columns.Contains(addedColumn));
  153. }
  154. }
  155. [Test]
  156. public void RemoveColumn()
  157. {
  158. CreateAlterMeTable();
  159. MsSqlAdapter dao = GetMsSqlAdapter();
  160. using (IDbConnection conn = GetConnection())
  161. {
  162. conn.Open();
  163. IDbCommand cmd = dao.DropColumns(conn, "alter_me", "remove_me");
  164. cmd.ExecuteNonQuery();
  165. Database db = dao.GetDatabase(conn, testDatabase.Name);
  166. Table tbl = db.Tables.Single(t => t.Name.Equals("alter_me"));
  167. Assert.IsTrue(tbl.Columns.DoesNotContain(col => col.Name == "remove_me"));
  168. conn.Close();
  169. }
  170. }
  171. [Test]
  172. public void AlterColumn_ChangeName()
  173. {
  174. string newColumnName = "new_column_name";
  175. using (var conn = IoC.Resolve<IDbConnection>() as SqlConnection)
  176. {
  177. conn.Open();
  178. MsSqlAdapter adapter = GetMsSqlAdapter();
  179. Column idColumn = GetIdColumn();
  180. Column oldColumn = new Column("old_column", DbType.String);
  181. Table table = new Table("alter_test", idColumn, oldColumn);
  182. using (IDbCommand cmd = adapter.CreateTable(conn, table))
  183. cmd.ExecuteNonQuery();
  184. using (IDbCommand cmd = adapter.RenameColumn(conn, oldColumn, newColumnName))
  185. cmd.ExecuteNonQuery();
  186. Database db = adapter.GetDatabase(conn, testDatabase.Name);
  187. var updatedTable = db.Tables.Single(tbl => tbl.Equals(table));
  188. var updatedColumn = updatedTable.Columns.SingleOrDefault(col => col.Name.Equals(newColumnName));
  189. Assert.IsNotNull(updatedColumn, "Column rename failed.");
  190. conn.Close();
  191. }
  192. }
  193. [Test]
  194. public void AlterColumn_ChangeType()
  195. {
  196. const string decimalColumnName = "datatype_col_decimal";
  197. const string tableName = "alter_test";
  198. using (IDbConnection conn = GetConnection())
  199. {
  200. conn.Open();
  201. MsSqlAdapter dao = GetMsSqlAdapter();
  202. Column idColumn = GetIdColumn();
  203. Column decimalColumn = new Column(decimalColumnName, DbType.Decimal);
  204. Table table = new Table(tableName, idColumn, decimalColumn);
  205. using (IDbCommand cmd = dao.CreateTable(conn, table))
  206. cmd.ExecuteNonQuery();
  207. var modifiedColumn = decimalColumn.CloneColumn();
  208. modifiedColumn.DataType = DbType.StringFixedLength;
  209. modifiedColumn.Length = 255;
  210. using (IDbCommand cmd = dao.AlterColumn(conn, decimalColumn, modifiedColumn))
  211. cmd.ExecuteNonQuery();
  212. Assert.IsTrue(MsSqlUtility.ColumnIsOfDataType(conn, testDatabase.Name, tableName, decimalColumnName, "nchar"),
  213. "Changing datatype of column failed.");
  214. conn.Close();
  215. }
  216. }
  217. [Test]
  218. public void AddForeignKey()
  219. {
  220. MsSqlAdapter adapter = GetAdapter(environment);
  221. using (var conn = environment.CreateConnection(adapter))
  222. {
  223. conn.Open();
  224. string pkTableName = "pk_table";
  225. string fkTableName = "fk_table";
  226. Table table = new Table(pkTableName,
  227. new Column("id", DbType.Int32, ColumnAttributes.PrimaryKey | ColumnAttributes.Identity),
  228. new Column("fk_tableId", DbType.Int32, ColumnAttributes.NotNull));
  229. Table referenceTable = new Table(fkTableName,
  230. new Column("Id", DbType.Int32, ColumnAttributes.PrimaryKey | ColumnAttributes.Identity));
  231. using (IDbTransaction trans = conn.BeginTransaction())
  232. {
  233. using (IDbCommand cmd = adapter.CreateTable(conn, table))
  234. {
  235. cmd.Transaction = trans;
  236. cmd.ExecuteNonQuery();
  237. }
  238. using (IDbCommand cmd = adapter.CreateTable(conn, referenceTable))
  239. {
  240. cmd.Transaction = trans;
  241. cmd.ExecuteNonQuery();
  242. }
  243. trans.Commit();
  244. }
  245. using (IDbCommand cmd = adapter.AddForeignKey(conn, pkTableName, fkTableName, "FK_BLEH_BLAH", new KeyValuePair<string, string>("fk_tableId", "Id")))
  246. cmd.ExecuteNonQuery();
  247. Assert.IsTrue(MsSqlUtility.ForeignKeyExists(conn, testDatabase.Name, "FK_BLEH_BLAH"), "Foreign Key not added.");
  248. conn.Close();
  249. }
  250. }
  251. [Test]
  252. public void AlterTable_RemoveForeignKey()
  253. {
  254. const string pkTableName = "pk_table";
  255. const string fkTableName = "fk_table";
  256. const string fkColumnName = "foreign_key_test";
  257. const string fkName = "FK_BLEH_BLUR";
  258. using (var conn = IoC.Resolve<IDbConnection>())
  259. {
  260. conn.Open();
  261. using (IDbTransaction trans = conn.BeginTransaction())
  262. {
  263. using (IDbCommand cmd = conn.CreateCommand())
  264. {
  265. cmd.CommandText = String.Format("CREATE TABLE {0} ([id] int primary key identity not null);", pkTableName);
  266. cmd.Transaction = trans;
  267. cmd.ExecuteNonQuery();
  268. }
  269. using (IDbCommand cmd = conn.CreateCommand())
  270. {
  271. cmd.CommandText = String.Format("CREATE TABLE {0} ([id] int primary key identity not null, [{1}] int not null);",
  272. fkTableName, fkColumnName);
  273. cmd.Transaction = trans;
  274. cmd.ExecuteNonQuery();
  275. }
  276. using (IDbCommand cmd = conn.CreateCommand())
  277. {
  278. cmd.CommandText = String.Format("ALTER TABLE {0} ADD CONSTRAINT {1} FOREIGN KEY ({2}) REFERENCES {3} ({4});",
  279. fkTableName, fkName, fkColumnName, pkTableName, "id");
  280. cmd.Transaction = trans;
  281. cmd.ExecuteNonQuery();
  282. }
  283. trans.Commit();
  284. }
  285. MsSqlAdapter dao = GetMsSqlAdapter();
  286. using (IDbCommand cmd = dao.DropForeignKey(conn, fkTableName, fkName))
  287. cmd.ExecuteNonQuery();
  288. Assert.IsFalse(MsSqlUtility.ForeignKeyExists(conn, testDatabase.Name, fkName));
  289. conn.Close();
  290. }
  291. }
  292. [Test]
  293. public void Create_unique_index_on_two_columns()
  294. {
  295. string colToIndexName = "col_to_index";
  296. string tableName = "table_name";
  297. using (var conn = IoC.Resolve<IDbConnection>())
  298. {
  299. conn.Open();
  300. using (IDbCommand cmd = conn.CreateCommand())
  301. {
  302. cmd.CommandText = string.Format("CREATE TABLE {0} ([id] int primary key not null, [{1}] nvarchar(200))", tableName,
  303. colToIndexName);
  304. cmd.ExecuteNonQuery();
  305. }
  306. MsSqlAdapter adapter = GetMsSqlAdapter();
  307. var index = new Index("IX_Test", new Table(tableName), true, new Hash(),
  308. GetIdColumn(),
  309. new MigrationBase.String(colToIndexName) { Length = 200});
  310. IDbCommand createIndexCommand = adapter.CreateIndex(index, conn);
  311. Console.WriteLine(createIndexCommand.CommandText);
  312. createIndexCommand.ExecuteNonQuery();
  313. conn.Close();
  314. }
  315. }
  316. private MsSqlAdapter GetAdapter(MiteEnvironment environment)
  317. {
  318. return GetMsSqlAdapter();
  319. }
  320. /// <summary>
  321. /// Create a table with name "test" and an id int32 identity column.
  322. /// </summary>
  323. private static Table GetTable(params Column[] columns)
  324. {
  325. var columnList = new List<Column>();
  326. columnList.Add(GetIdColumn());
  327. columnList.AddRange(columns);
  328. return new Table("test", columnList.ToArray());
  329. }
  330. private void CreateAlterMeTable()
  331. {
  332. using (var conn = IoC.Resolve<IDbConnection>())
  333. {
  334. conn.Open();
  335. conn.ChangeDatabase(testDatabase.Name);
  336. using (IDbCommand cmd = conn.CreateCommand())
  337. {
  338. cmd.CommandText =
  339. String.Format("CREATE TABLE [alter_me] ([id] int not null identity primary key, [remove_me] nchar(2) null)");
  340. cmd.ExecuteNonQuery();
  341. }
  342. conn.Close();
  343. }
  344. }
  345. protected MsSqlAdapter GetMsSqlAdapter()
  346. {
  347. var adapter = new MsSqlAdapter();
  348. return adapter;
  349. }
  350. protected IDbConnection GetConnection()
  351. {
  352. var adapter = new MsSqlAdapter();
  353. IDbConnection conn = adapter.CreateConnection(
  354. environment.Host,
  355. environment.Database,
  356. environment.Username,
  357. environment.Password,
  358. environment.Options);
  359. return conn;
  360. }
  361. protected IDbConnection GetConnection(Adapter adapter)
  362. {
  363. return adapter.CreateConnection(environment.Host, environment.Database, environment.Username, environment.Password,
  364. environment.Options);
  365. }
  366. private static Column GetIdColumn()
  367. {
  368. return new Column("Id", DbType.Int32, ColumnAttributes.Identity | ColumnAttributes.PrimaryKey);
  369. }
  370. private static void AssertTableExists(string tableName)
  371. {
  372. using (var conn = IoC.Resolve<IDbConnection>() as SqlConnection)
  373. {
  374. conn.Open();
  375. IEnumerable<string> tableNames = MsSqlUtility.GetTableNamesInDatabase(DATABASE_NAME, conn);
  376. Assert.IsTrue(tableNames.Contains(tableName));
  377. conn.Close();
  378. }
  379. }
  380. private static void AssertTableDoesNotExist(string tableName)
  381. {
  382. using (var conn = IoC.Resolve<IDbConnection>())
  383. {
  384. conn.Open();
  385. IEnumerable<string> tableNames = MsSqlUtility.GetTableNamesInDatabase(DATABASE_NAME, conn);
  386. Assert.IsFalse(tableNames.Contains(tableName));
  387. }
  388. }
  389. private readonly Database testDatabase = new Database(DATABASE_NAME);
  390. }
  391. }