MSSQLManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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 OpenMetaverse;
  34. using log4net;
  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. [Obsolete("Do not use!")]
  93. protected static string defineTable(DataTable dt)
  94. {
  95. string sql = "create table " + dt.TableName + "(";
  96. string subsql = String.Empty;
  97. foreach (DataColumn col in dt.Columns)
  98. {
  99. if (subsql.Length > 0)
  100. {
  101. // a map function would rock so much here
  102. subsql += ",\n";
  103. }
  104. subsql += col.ColumnName + " " + SqlType(col.DataType);
  105. if (col == dt.PrimaryKey[0])
  106. {
  107. subsql += " primary key";
  108. }
  109. }
  110. sql += subsql;
  111. sql += ")";
  112. return sql;
  113. }
  114. #endregion
  115. /// <summary>
  116. /// Type conversion function
  117. /// </summary>
  118. /// <param name="type">a type</param>
  119. /// <returns>a sqltype</returns>
  120. /// <remarks>this is something we'll need to implement for each db slightly differently.</remarks>
  121. [Obsolete("Used by a obsolete methods")]
  122. public static string SqlType(Type type)
  123. {
  124. if (type == typeof(String))
  125. {
  126. return "varchar(255)";
  127. }
  128. if (type == typeof(Int32))
  129. {
  130. return "integer";
  131. }
  132. if (type == typeof(Double))
  133. {
  134. return "float";
  135. }
  136. if (type == typeof(Byte[]))
  137. {
  138. return "image";
  139. }
  140. return "varchar(255)";
  141. }
  142. /// <summary>
  143. /// Type conversion to a SQLDbType functions
  144. /// </summary>
  145. /// <param name="type"></param>
  146. /// <returns></returns>
  147. internal SqlDbType DbtypeFromType(Type type)
  148. {
  149. if (type == typeof(string))
  150. {
  151. return SqlDbType.VarChar;
  152. }
  153. if (type == typeof(double))
  154. {
  155. return SqlDbType.Float;
  156. }
  157. if (type == typeof(Single))
  158. {
  159. return SqlDbType.Float;
  160. }
  161. if (type == typeof(int))
  162. {
  163. return SqlDbType.Int;
  164. }
  165. if (type == typeof(bool))
  166. {
  167. return SqlDbType.Bit;
  168. }
  169. if (type == typeof(UUID))
  170. {
  171. return SqlDbType.VarChar;
  172. }
  173. if (type == typeof(sbyte))
  174. {
  175. return SqlDbType.Int;
  176. }
  177. if (type == typeof(Byte[]))
  178. {
  179. return SqlDbType.Image;
  180. }
  181. if (type == typeof(uint) || type == typeof(ushort))
  182. {
  183. return SqlDbType.Int;
  184. }
  185. if (type == typeof(ulong))
  186. {
  187. return SqlDbType.BigInt;
  188. }
  189. return SqlDbType.VarChar;
  190. }
  191. /// <summary>
  192. /// Creates value for parameter.
  193. /// </summary>
  194. /// <param name="value">The value.</param>
  195. /// <returns></returns>
  196. private static object CreateParameterValue(object value)
  197. {
  198. Type valueType = value.GetType();
  199. if (valueType == typeof(UUID))
  200. {
  201. return value.ToString();
  202. }
  203. if (valueType == typeof(OpenMetaverse.UUID))
  204. {
  205. return value.ToString();
  206. }
  207. if (valueType == typeof(bool))
  208. {
  209. return (bool)value ? 1 : 0;
  210. }
  211. if (valueType == typeof(Byte[]))
  212. {
  213. return value;
  214. }
  215. if (valueType == typeof(int))
  216. {
  217. return value;
  218. }
  219. return value;
  220. }
  221. /// <summary>
  222. /// Create a parameter for a command
  223. /// </summary>
  224. /// <param name="parameterName">Name of the parameter.</param>
  225. /// <param name="parameterObject">parameter object.</param>
  226. /// <returns></returns>
  227. internal SqlParameter CreateParameter(string parameterName, object parameterObject)
  228. {
  229. return CreateParameter(parameterName, parameterObject, false);
  230. }
  231. /// <summary>
  232. /// Creates the parameter for a command.
  233. /// </summary>
  234. /// <param name="parameterName">Name of the parameter.</param>
  235. /// <param name="parameterObject">parameter object.</param>
  236. /// <param name="parameterOut">if set to <c>true</c> parameter is a output parameter</param>
  237. /// <returns></returns>
  238. internal SqlParameter CreateParameter(string parameterName, object parameterObject, bool parameterOut)
  239. {
  240. //Tweak so we dont always have to add @ sign
  241. if (!parameterName.StartsWith("@")) parameterName = "@" + parameterName;
  242. //HACK if object is null, it is turned into a string, there are no nullable type till now
  243. if (parameterObject == null) parameterObject = "";
  244. SqlParameter parameter = new SqlParameter(parameterName, DbtypeFromType(parameterObject.GetType()));
  245. if (parameterOut)
  246. {
  247. parameter.Direction = ParameterDirection.Output;
  248. }
  249. else
  250. {
  251. parameter.Direction = ParameterDirection.Input;
  252. parameter.Value = CreateParameterValue(parameterObject);
  253. }
  254. return parameter;
  255. }
  256. private static readonly Dictionary<string, string> emptyDictionary = new Dictionary<string, string>();
  257. /// <summary>
  258. /// Run a query and return a sql db command
  259. /// </summary>
  260. /// <param name="sql">The SQL query.</param>
  261. /// <returns></returns>
  262. internal AutoClosingSqlCommand Query(string sql)
  263. {
  264. return Query(sql, emptyDictionary);
  265. }
  266. /// <summary>
  267. /// Runs a query with protection against SQL Injection by using parameterised input.
  268. /// </summary>
  269. /// <param name="sql">The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y</param>
  270. /// <param name="parameters">The parameters - index so that @y is indexed as 'y'</param>
  271. /// <returns>A Sql DB Command</returns>
  272. internal AutoClosingSqlCommand Query(string sql, Dictionary<string, string> parameters)
  273. {
  274. SqlCommand dbcommand = DatabaseConnection().CreateCommand();
  275. dbcommand.CommandText = sql;
  276. foreach (KeyValuePair<string, string> param in parameters)
  277. {
  278. dbcommand.Parameters.AddWithValue(param.Key, param.Value);
  279. }
  280. return new AutoClosingSqlCommand(dbcommand);
  281. }
  282. /// <summary>
  283. /// Runs a query with protection against SQL Injection by using parameterised input.
  284. /// </summary>
  285. /// <param name="sql">The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y</param>
  286. /// <param name="sqlParameter">A parameter - use createparameter to create parameter</param>
  287. /// <returns></returns>
  288. internal AutoClosingSqlCommand Query(string sql, SqlParameter sqlParameter)
  289. {
  290. SqlCommand dbcommand = DatabaseConnection().CreateCommand();
  291. dbcommand.CommandText = sql;
  292. dbcommand.Parameters.Add(sqlParameter);
  293. return new AutoClosingSqlCommand(dbcommand);
  294. }
  295. /// <summary>
  296. /// Checks if we need to do some migrations to the database
  297. /// </summary>
  298. /// <param name="migrationStore">migrationStore.</param>
  299. public void CheckMigration(string migrationStore)
  300. {
  301. using (SqlConnection connection = DatabaseConnection())
  302. {
  303. Assembly assem = GetType().Assembly;
  304. MSSQLMigration migration = new MSSQLMigration(connection, assem, migrationStore);
  305. migration.Update();
  306. connection.Close();
  307. }
  308. }
  309. #region Old Testtable functions
  310. /// <summary>
  311. /// Execute a SQL statement stored in a resource, as a string
  312. /// </summary>
  313. /// <param name="name">the ressource string</param>
  314. public void ExecuteResourceSql(string name)
  315. {
  316. using (IDbCommand cmd = Query(getResourceString(name), new Dictionary<string, string>()))
  317. {
  318. cmd.ExecuteNonQuery();
  319. }
  320. }
  321. /// <summary>
  322. /// Given a list of tables, return the version of the tables, as seen in the database
  323. /// </summary>
  324. /// <param name="tableList"></param>
  325. public void GetTableVersion(Dictionary<string, string> tableList)
  326. {
  327. Dictionary<string, string> param = new Dictionary<string, string>();
  328. param["dbname"] = new SqlConnectionStringBuilder(connectionString).InitialCatalog;
  329. using (IDbCommand tablesCmd =
  330. Query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG=@dbname", param))
  331. using (IDataReader tables = tablesCmd.ExecuteReader())
  332. {
  333. while (tables.Read())
  334. {
  335. try
  336. {
  337. string tableName = (string)tables["TABLE_NAME"];
  338. if (tableList.ContainsKey(tableName))
  339. tableList[tableName] = tableName;
  340. }
  341. catch (Exception e)
  342. {
  343. m_log.Error(e.ToString());
  344. }
  345. }
  346. tables.Close();
  347. }
  348. }
  349. /// <summary>
  350. ///
  351. /// </summary>
  352. /// <param name="name"></param>
  353. /// <returns></returns>
  354. private string getResourceString(string name)
  355. {
  356. Assembly assem = GetType().Assembly;
  357. string[] names = assem.GetManifestResourceNames();
  358. foreach (string s in names)
  359. if (s.EndsWith(name))
  360. using (Stream resource = assem.GetManifestResourceStream(s))
  361. {
  362. using (StreamReader resourceReader = new StreamReader(resource))
  363. {
  364. string resourceString = resourceReader.ReadToEnd();
  365. return resourceString;
  366. }
  367. }
  368. throw new Exception(string.Format("Resource '{0}' was not found", name));
  369. }
  370. #endregion
  371. /// <summary>
  372. /// Returns the version of this DB provider
  373. /// </summary>
  374. /// <returns>A string containing the DB provider</returns>
  375. public string getVersion()
  376. {
  377. Module module = GetType().Module;
  378. // string dllName = module.Assembly.ManifestModule.Name;
  379. Version dllVersion = module.Assembly.GetName().Version;
  380. return
  381. string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build,
  382. dllVersion.Revision);
  383. }
  384. }
  385. }