MSSQLManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSim Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Data;
  30. using System.Data.SqlClient;
  31. using System.IO;
  32. using System.Reflection;
  33. using log4net;
  34. using OpenMetaverse;
  35. namespace OpenSim.Data.MSSQL
  36. {
  37. /// <summary>
  38. /// A management class for the MS SQL Storage Engine
  39. /// </summary>
  40. public class MSSQLManager
  41. {
  42. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  43. /// <summary>
  44. /// Connection string for ADO.net
  45. /// </summary>
  46. private readonly string connectionString;
  47. public MSSQLManager(string dataSource, string initialCatalog, string persistSecurityInfo, string userId,
  48. string password)
  49. {
  50. SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
  51. builder.DataSource = dataSource;
  52. builder.InitialCatalog = initialCatalog;
  53. builder.PersistSecurityInfo = Convert.ToBoolean(persistSecurityInfo);
  54. builder.UserID = userId;
  55. builder.Password = password;
  56. builder.ApplicationName = Assembly.GetEntryAssembly().Location;
  57. connectionString = builder.ToString();
  58. }
  59. /// <summary>
  60. /// Initialize the manager and set the connectionstring
  61. /// </summary>
  62. /// <param name="connection"></param>
  63. public MSSQLManager(string connection)
  64. {
  65. connectionString = connection;
  66. }
  67. public SqlConnection DatabaseConnection()
  68. {
  69. SqlConnection conn = new SqlConnection(connectionString);
  70. //TODO is this good??? Opening connection here
  71. conn.Open();
  72. return conn;
  73. }
  74. #region Obsolete functions, can be removed!
  75. /// <summary>
  76. ///
  77. /// </summary>
  78. /// <param name="dt"></param>
  79. /// <param name="name"></param>
  80. /// <param name="type"></param>
  81. [Obsolete("Do not use!")]
  82. protected static void createCol(DataTable dt, string name, Type type)
  83. {
  84. DataColumn col = new DataColumn(name, type);
  85. dt.Columns.Add(col);
  86. }
  87. /// <summary>
  88. /// Define Table function
  89. /// </summary>
  90. /// <param name="dt"></param>
  91. /// <returns></returns>
  92. /*
  93. [Obsolete("Do not use!")]
  94. protected static string defineTable(DataTable dt)
  95. {
  96. string sql = "create table " + dt.TableName + "(";
  97. string subsql = String.Empty;
  98. foreach (DataColumn col in dt.Columns)
  99. {
  100. if (subsql.Length > 0)
  101. {
  102. // a map function would rock so much here
  103. subsql += ",\n";
  104. }
  105. subsql += col.ColumnName + " " + SqlType(col.DataType);
  106. if (col == dt.PrimaryKey[0])
  107. {
  108. subsql += " primary key";
  109. }
  110. }
  111. sql += subsql;
  112. sql += ")";
  113. return sql;
  114. }
  115. */
  116. #endregion
  117. /// <summary>
  118. /// Type conversion function
  119. /// </summary>
  120. /// <param name="type">a type</param>
  121. /// <returns>a sqltype</returns>
  122. /// <remarks>this is something we'll need to implement for each db slightly differently.</remarks>
  123. /*
  124. [Obsolete("Used by a obsolete methods")]
  125. public static string SqlType(Type type)
  126. {
  127. if (type == typeof(String))
  128. {
  129. return "varchar(255)";
  130. }
  131. if (type == typeof(Int32))
  132. {
  133. return "integer";
  134. }
  135. if (type == typeof(Double))
  136. {
  137. return "float";
  138. }
  139. if (type == typeof(Byte[]))
  140. {
  141. return "image";
  142. }
  143. return "varchar(255)";
  144. }
  145. */
  146. /// <summary>
  147. /// Type conversion to a SQLDbType functions
  148. /// </summary>
  149. /// <param name="type"></param>
  150. /// <returns></returns>
  151. internal SqlDbType DbtypeFromType(Type type)
  152. {
  153. if (type == typeof(string))
  154. {
  155. return SqlDbType.VarChar;
  156. }
  157. if (type == typeof(double))
  158. {
  159. return SqlDbType.Float;
  160. }
  161. if (type == typeof(Single))
  162. {
  163. return SqlDbType.Float;
  164. }
  165. if (type == typeof(int))
  166. {
  167. return SqlDbType.Int;
  168. }
  169. if (type == typeof(bool))
  170. {
  171. return SqlDbType.Bit;
  172. }
  173. if (type == typeof(UUID))
  174. {
  175. return SqlDbType.UniqueIdentifier;
  176. }
  177. if (type == typeof(sbyte))
  178. {
  179. return SqlDbType.Int;
  180. }
  181. if (type == typeof(Byte[]))
  182. {
  183. return SqlDbType.Image;
  184. }
  185. if (type == typeof(uint) || type == typeof(ushort))
  186. {
  187. return SqlDbType.Int;
  188. }
  189. if (type == typeof(ulong))
  190. {
  191. return SqlDbType.BigInt;
  192. }
  193. return SqlDbType.VarChar;
  194. }
  195. /// <summary>
  196. /// Creates value for parameter.
  197. /// </summary>
  198. /// <param name="value">The value.</param>
  199. /// <returns></returns>
  200. private static object CreateParameterValue(object value)
  201. {
  202. Type valueType = value.GetType();
  203. if (valueType == typeof(UUID)) //TODO check if this works
  204. {
  205. return ((UUID) value).Guid;
  206. }
  207. if (valueType == typeof(UUID))
  208. {
  209. return ((UUID)value).Guid;
  210. }
  211. if (valueType == typeof(bool))
  212. {
  213. return (bool)value ? 1 : 0;
  214. }
  215. if (valueType == typeof(Byte[]))
  216. {
  217. return value;
  218. }
  219. if (valueType == typeof(int))
  220. {
  221. return value;
  222. }
  223. return value;
  224. }
  225. /// <summary>
  226. /// Create a parameter for a command
  227. /// </summary>
  228. /// <param name="parameterName">Name of the parameter.</param>
  229. /// <param name="parameterObject">parameter object.</param>
  230. /// <returns></returns>
  231. internal SqlParameter CreateParameter(string parameterName, object parameterObject)
  232. {
  233. return CreateParameter(parameterName, parameterObject, false);
  234. }
  235. /// <summary>
  236. /// Creates the parameter for a command.
  237. /// </summary>
  238. /// <param name="parameterName">Name of the parameter.</param>
  239. /// <param name="parameterObject">parameter object.</param>
  240. /// <param name="parameterOut">if set to <c>true</c> parameter is a output parameter</param>
  241. /// <returns></returns>
  242. internal SqlParameter CreateParameter(string parameterName, object parameterObject, bool parameterOut)
  243. {
  244. //Tweak so we dont always have to add @ sign
  245. if (!parameterName.StartsWith("@")) parameterName = "@" + parameterName;
  246. //HACK if object is null, it is turned into a string, there are no nullable type till now
  247. if (parameterObject == null) parameterObject = "";
  248. SqlParameter parameter = new SqlParameter(parameterName, DbtypeFromType(parameterObject.GetType()));
  249. if (parameterOut)
  250. {
  251. parameter.Direction = ParameterDirection.Output;
  252. }
  253. else
  254. {
  255. parameter.Direction = ParameterDirection.Input;
  256. parameter.Value = CreateParameterValue(parameterObject);
  257. }
  258. return parameter;
  259. }
  260. private static readonly Dictionary<string, string> emptyDictionary = new Dictionary<string, string>();
  261. /// <summary>
  262. /// Run a query and return a sql db command
  263. /// </summary>
  264. /// <param name="sql">The SQL query.</param>
  265. /// <returns></returns>
  266. internal AutoClosingSqlCommand Query(string sql)
  267. {
  268. return Query(sql, emptyDictionary);
  269. }
  270. /// <summary>
  271. /// Runs a query with protection against SQL Injection by using parameterised input.
  272. /// </summary>
  273. /// <param name="sql">The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y</param>
  274. /// <param name="parameters">The parameters - index so that @y is indexed as 'y'</param>
  275. /// <returns>A Sql DB Command</returns>
  276. internal AutoClosingSqlCommand Query(string sql, Dictionary<string, string> parameters)
  277. {
  278. SqlCommand dbcommand = DatabaseConnection().CreateCommand();
  279. dbcommand.CommandText = sql;
  280. foreach (KeyValuePair<string, string> param in parameters)
  281. {
  282. dbcommand.Parameters.AddWithValue(param.Key, param.Value);
  283. }
  284. return new AutoClosingSqlCommand(dbcommand);
  285. }
  286. /// <summary>
  287. /// Runs a query with protection against SQL Injection by using parameterised input.
  288. /// </summary>
  289. /// <param name="sql">The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y</param>
  290. /// <param name="sqlParameter">A parameter - use createparameter to create parameter</param>
  291. /// <returns></returns>
  292. internal AutoClosingSqlCommand Query(string sql, SqlParameter sqlParameter)
  293. {
  294. SqlCommand dbcommand = DatabaseConnection().CreateCommand();
  295. dbcommand.CommandText = sql;
  296. dbcommand.Parameters.Add(sqlParameter);
  297. return new AutoClosingSqlCommand(dbcommand);
  298. }
  299. /// <summary>
  300. /// Checks if we need to do some migrations to the database
  301. /// </summary>
  302. /// <param name="migrationStore">migrationStore.</param>
  303. public void CheckMigration(string migrationStore)
  304. {
  305. using (SqlConnection connection = DatabaseConnection())
  306. {
  307. Assembly assem = GetType().Assembly;
  308. MSSQLMigration migration = new MSSQLMigration(connection, assem, migrationStore);
  309. migration.Update();
  310. connection.Close();
  311. }
  312. }
  313. #region Old Testtable functions
  314. /// <summary>
  315. /// Execute a SQL statement stored in a resource, as a string
  316. /// </summary>
  317. /// <param name="name">the ressource string</param>
  318. public void ExecuteResourceSql(string name)
  319. {
  320. using (IDbCommand cmd = Query(getResourceString(name), new Dictionary<string, string>()))
  321. {
  322. cmd.ExecuteNonQuery();
  323. }
  324. }
  325. /// <summary>
  326. /// Given a list of tables, return the version of the tables, as seen in the database
  327. /// </summary>
  328. /// <param name="tableList"></param>
  329. public void GetTableVersion(Dictionary<string, string> tableList)
  330. {
  331. Dictionary<string, string> param = new Dictionary<string, string>();
  332. param["dbname"] = new SqlConnectionStringBuilder(connectionString).InitialCatalog;
  333. using (IDbCommand tablesCmd =
  334. Query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG=@dbname", param))
  335. using (IDataReader tables = tablesCmd.ExecuteReader())
  336. {
  337. while (tables.Read())
  338. {
  339. try
  340. {
  341. string tableName = (string)tables["TABLE_NAME"];
  342. if (tableList.ContainsKey(tableName))
  343. tableList[tableName] = tableName;
  344. }
  345. catch (Exception e)
  346. {
  347. m_log.Error(e.ToString());
  348. }
  349. }
  350. tables.Close();
  351. }
  352. }
  353. /// <summary>
  354. ///
  355. /// </summary>
  356. /// <param name="name"></param>
  357. /// <returns></returns>
  358. private string getResourceString(string name)
  359. {
  360. Assembly assem = GetType().Assembly;
  361. string[] names = assem.GetManifestResourceNames();
  362. foreach (string s in names)
  363. if (s.EndsWith(name))
  364. using (Stream resource = assem.GetManifestResourceStream(s))
  365. {
  366. using (StreamReader resourceReader = new StreamReader(resource))
  367. {
  368. string resourceString = resourceReader.ReadToEnd();
  369. return resourceString;
  370. }
  371. }
  372. throw new Exception(string.Format("Resource '{0}' was not found", name));
  373. }
  374. #endregion
  375. /// <summary>
  376. /// Returns the version of this DB provider
  377. /// </summary>
  378. /// <returns>A string containing the DB provider</returns>
  379. public string getVersion()
  380. {
  381. Module module = GetType().Module;
  382. // string dllName = module.Assembly.ManifestModule.Name;
  383. Version dllVersion = module.Assembly.GetName().Version;
  384. return
  385. string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build,
  386. dllVersion.Revision);
  387. }
  388. }
  389. }