ConnectionManager.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. // ConnectionManager.cs - Singleton ConnectionManager class to manage
  2. // database connections for test cases.
  3. //
  4. // Authors:
  5. // Sureshkumar T ([email protected])
  6. //
  7. // Copyright Novell Inc., and the individuals listed on the
  8. // ChangeLog entries.
  9. //
  10. //
  11. // Permission is hereby granted, free of charge, to any person
  12. // obtaining a copy of this software and associated documentation
  13. // files (the "Software"), to deal in the Software without
  14. // restriction, including without limitation the rights to use, copy,
  15. // modify, merge, publish, distribute, sublicense, and/or sell copies
  16. // of the Software, and to permit persons to whom the Software is
  17. // furnished to do so, subject to the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  26. // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  27. // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  28. // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  29. // SOFTWARE.
  30. using System;
  31. using System.Collections.Generic;
  32. using System.Data;
  33. using System.Data.Common;
  34. #if !NO_ODBC
  35. using System.Data.Odbc;
  36. #endif
  37. using System.Data.SqlClient;
  38. using System.IO;
  39. using System.Linq;
  40. using System.Text.RegularExpressions;
  41. using NUnit.Framework;
  42. namespace MonoTests.System.Data.Connected
  43. {
  44. public class ConnectionManager
  45. {
  46. private static ConnectionManager instance;
  47. private ConnectionHolder<SqlConnection> sql;
  48. private const string OdbcEnvVar = "SYSTEM_DATA_ODBC_V2";
  49. private const string SqlEnvVar = "SYSTEM_DATA_MSSQL_V2";
  50. private ConnectionManager ()
  51. {
  52. //Environment.SetEnvironmentVariable(OdbcEnvVar, @"Driver={MySQL ODBC 5.3 Unicode Driver};server=127.0.0.1;uid=sa;pwd=qwerty123;");
  53. //Environment.SetEnvironmentVariable(SqlEnvVar, @"server=127.0.0.1;database=master;user id=sa;password=qwerty123");
  54. // Generate a random db name
  55. DatabaseName = "monotest" + Guid.NewGuid().ToString().Substring(0, 7);
  56. sql = CreateSqlConfig (SqlEnvVar);
  57. if (sql != null)
  58. CreateMssqlDatabase();
  59. #if !NO_ODBC
  60. odbc = CreateOdbcConfig (OdbcEnvVar);
  61. if (odbc != null)
  62. CreateMysqlDatabase();
  63. #endif
  64. }
  65. static ConnectionHolder<SqlConnection> CreateSqlConfig (string envVarName)
  66. {
  67. string connectionString = Environment.GetEnvironmentVariable (envVarName);
  68. if (string.IsNullOrEmpty (connectionString))
  69. return null;
  70. SqlConnection connection;
  71. #if MOBILE
  72. connection = new SqlConnection ();
  73. #else
  74. DbProviderFactory factory = DbProviderFactories.GetFactory ("System.Data.SqlClient");
  75. connection = (SqlConnection)factory.CreateConnection ();
  76. #endif
  77. var engine = new EngineConfig {
  78. Type = EngineType.SQLServer,
  79. ClientVersion = 9,
  80. QuoteCharacter = "&quot;",
  81. SupportsMicroseconds = true,
  82. SupportsUniqueIdentifier = true,
  83. SupportsTimestamp = true,
  84. };
  85. return new ConnectionHolder<SqlConnection> (engine, connection, connectionString);
  86. }
  87. #if !NO_ODBC
  88. static ConnectionHolder<OdbcConnection> CreateOdbcConfig (string envVarName)
  89. {
  90. string connectionString = Environment.GetEnvironmentVariable (envVarName);
  91. if (string.IsNullOrEmpty (connectionString))
  92. return null;
  93. DbProviderFactory factory = DbProviderFactories.GetFactory ("System.Data.Odbc");
  94. var connection = (OdbcConnection)factory.CreateConnection ();
  95. var engine = new EngineConfig {
  96. Type = EngineType.MySQL,
  97. QuoteCharacter = "`",
  98. RemovesTrailingSpaces = true,
  99. EmptyBinaryAsNull = true,
  100. SupportsDate = true,
  101. SupportsTime = true
  102. };
  103. return new ConnectionHolder<OdbcConnection> (engine, connection, connectionString);
  104. }
  105. #endif
  106. private void CreateMssqlDatabase()
  107. {
  108. DBHelper.ExecuteNonQuery(sql.Connection, $"CREATE DATABASE [{DatabaseName}]");
  109. sql.ConnectionString = sql.ConnectionString.Replace(sql.Connection.Database, DatabaseName);
  110. sql.CloseConnection();
  111. string query = File.ReadAllText(@"Test/ProviderTests/sql/sqlserver.sql");
  112. var queries = SplitSqlStatements(query);
  113. foreach (var subQuery in queries)
  114. {
  115. DBHelper.ExecuteNonQuery(sql.Connection, subQuery);
  116. }
  117. }
  118. #if !NO_ODBC
  119. private void CreateMysqlDatabase()
  120. {
  121. DBHelper.ExecuteNonQuery(odbc.Connection, $"CREATE DATABASE {DatabaseName}");
  122. odbc.Connection.ChangeDatabase(DatabaseName);
  123. odbc.ConnectionString += $"database={DatabaseName}";
  124. string query = File.ReadAllText("Test/ProviderTests/sql/MySQL_5.sql");
  125. var groups = query.Replace("delimiter ", "")
  126. .Split(new[] { "//\n" }, StringSplitOptions.RemoveEmptyEntries);
  127. foreach (var subQuery in groups[0].Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).Concat(groups.Skip(1)))
  128. {
  129. DBHelper.ExecuteNonQuery(odbc.Connection, subQuery);
  130. }
  131. }
  132. #endif
  133. private void DropMssqlDatabase()
  134. {
  135. sql.Connection.ChangeDatabase("master");
  136. string query = $"ALTER DATABASE [{DatabaseName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;\nDROP DATABASE [{DatabaseName}]";
  137. DBHelper.ExecuteNonQuery(sql.Connection, query);
  138. }
  139. #if !NO_ODBC
  140. private void DropMysqlDatabase()
  141. {
  142. string query = $"DROP DATABASE [{DatabaseName}]";
  143. DBHelper.ExecuteNonQuery(odbc.Connection, query);
  144. }
  145. #endif
  146. // Split SQL script by "GO" statements
  147. private static IEnumerable<string> SplitSqlStatements(string sqlScript)
  148. {
  149. var statements = Regex.Split(sqlScript,
  150. $@"^[\t ]*GO[\t ]*\d*[\t ]*(?:--.*)?$",
  151. RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
  152. return statements.Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Trim(' ', '\r', '\n'));
  153. }
  154. public static ConnectionManager Instance => instance ?? (instance = new ConnectionManager());
  155. public string DatabaseName { get; }
  156. #if !NO_ODBC
  157. private ConnectionHolder<OdbcConnection> odbc;
  158. public ConnectionHolder<OdbcConnection> Odbc
  159. {
  160. get
  161. {
  162. if (odbc == null)
  163. Assert.Ignore($"{OdbcEnvVar} environment variable is not set");
  164. return odbc;
  165. }
  166. }
  167. #endif
  168. public ConnectionHolder<SqlConnection> Sql
  169. {
  170. get
  171. {
  172. if (sql == null)
  173. Assert.Ignore($"{SqlEnvVar} environment variable is not set");
  174. return sql;
  175. }
  176. }
  177. public void Close()
  178. {
  179. sql?.CloseConnection();
  180. #if !NO_ODBC
  181. odbc?.CloseConnection();
  182. #endif
  183. }
  184. }
  185. public class ConnectionHolder<TConnection> where TConnection : DbConnection
  186. {
  187. private TConnection connection;
  188. public EngineConfig EngineConfig { get; }
  189. public TConnection Connection
  190. {
  191. get
  192. {
  193. if (!(connection.State == ConnectionState.Closed ||
  194. connection.State == ConnectionState.Broken))
  195. connection.Close();
  196. connection.ConnectionString = ConnectionString;
  197. connection.Open();
  198. return connection;
  199. }
  200. }
  201. public void CloseConnection()
  202. {
  203. if (connection != null && connection.State != ConnectionState.Closed)
  204. connection.Close();
  205. }
  206. public string ConnectionString { get; set; }
  207. public ConnectionHolder(EngineConfig engineConfig, TConnection connection, string connectionString)
  208. {
  209. EngineConfig = engineConfig;
  210. this.connection = connection;
  211. ConnectionString = connectionString;
  212. }
  213. public bool IsAzure => ConnectionString.ToLower().Contains("database.windows.net");
  214. }
  215. }