NHibernateManager.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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.Reflection;
  29. using System.IO;
  30. using log4net;
  31. using NHibernate;
  32. using NHibernate.Cfg;
  33. using NHibernate.Tool.hbm2ddl;
  34. using OpenMetaverse;
  35. using Environment = NHibernate.Cfg.Environment;
  36. namespace OpenSim.Data.NHibernate
  37. {
  38. public class NHibernateManager
  39. {
  40. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  41. private string dialect;
  42. private Configuration configuration;
  43. private ISessionFactory sessionFactory;
  44. /// <summary>
  45. /// Parses the connection string and creates the NHibernate configuration
  46. /// </summary>
  47. /// <param name="connect">NHibernate dialect, driver and connection string separated by ';'</param>
  48. private void parseConnectionString(string connect)
  49. {
  50. // Split out the dialect, driver, and connect string
  51. char[] split = { ';' };
  52. string[] parts = connect.Split(split, 3);
  53. if (parts.Length != 3)
  54. {
  55. // TODO: make this a real exception type
  56. throw new Exception("Malformed Inventory connection string '" + connect + "'");
  57. }
  58. dialect = parts[0];
  59. // NHibernate setup
  60. configuration = new Configuration();
  61. configuration.SetProperty(Environment.ConnectionProvider,
  62. "NHibernate.Connection.DriverConnectionProvider");
  63. configuration.SetProperty(Environment.Dialect,
  64. "NHibernate.Dialect." + dialect);
  65. configuration.SetProperty(Environment.ConnectionDriver,
  66. "NHibernate.Driver." + parts[1]);
  67. configuration.SetProperty(Environment.ConnectionString, parts[2]);
  68. configuration.AddAssembly("OpenSim.Data.NHibernate");
  69. sessionFactory = configuration.BuildSessionFactory();
  70. }
  71. /// <summary>
  72. /// Runs migration for the the store in assembly
  73. /// </summary>
  74. /// <param name="dialect">Dialect in use</param>
  75. /// <param name="assembly">Assembly where migration files exist</param>
  76. /// <param name="store">Name of the store in use</param>
  77. private void runMigration(string dialect, Assembly assembly, string store)
  78. {
  79. // Migration subtype is the folder name under which migrations are stored. For mysql this folder is
  80. // MySQLDialect instead of MySQL5Dialect which is the dialect currently in use. To avoid renaming
  81. // this folder each time the mysql version changes creating simple mapping:
  82. String migrationSubType = dialect;
  83. if (dialect.StartsWith("MySQL"))
  84. {
  85. migrationSubType = "MySQLDialect";
  86. }
  87. Migration migration = new Migration((System.Data.Common.DbConnection)sessionFactory.ConnectionProvider.GetConnection(), assembly, migrationSubType, store);
  88. migration.Update();
  89. }
  90. /// <summary>
  91. /// Initiate NHibernate Manager
  92. /// </summary>
  93. /// <param name="connect">NHibernate dialect, driver and connection string separated by ';'</param>
  94. /// <param name="store">Name of the store</param>
  95. public NHibernateManager(string connect, string store)
  96. {
  97. parseConnectionString(connect);
  98. //To create sql file uncomment code below and write the name of the file
  99. //SchemaExport exp = new SchemaExport(cfg);
  100. //exp.SetOutputFile("nameofthefile.sql");
  101. //exp.Create(false, true);
  102. Assembly assembly = GetType().Assembly;
  103. runMigration(dialect, assembly, store);
  104. }
  105. /// <summary>
  106. /// Initiate NHibernate Manager with spesific assembly
  107. /// </summary>
  108. /// <param name="connect">NHibernate dialect, driver and connection string separated by ';'</param>
  109. /// <param name="store">Name of the store</param>
  110. /// <param name="assembly"></param>
  111. public NHibernateManager(string connect, string store, Assembly assembly)
  112. {
  113. parseConnectionString(connect);
  114. configuration.AddAssembly(assembly);
  115. runMigration(dialect, assembly, store);
  116. }
  117. public object Load(Type type, UUID uuid)
  118. {
  119. using (IStatelessSession session = sessionFactory.OpenStatelessSession())
  120. {
  121. object obj = null;
  122. try
  123. {
  124. obj = session.Get(type.FullName, uuid);
  125. }
  126. catch (Exception e)
  127. {
  128. m_log.ErrorFormat("[NHIBERNATE] {0} of id {1} loading threw exception: "+ e.ToString(), type.Name, uuid);
  129. }
  130. return obj;
  131. }
  132. }
  133. public bool Save(object obj)
  134. {
  135. try
  136. {
  137. using (IStatelessSession session = sessionFactory.OpenStatelessSession())
  138. {
  139. using (ITransaction transaction=session.BeginTransaction())
  140. {
  141. session.Insert(obj);
  142. transaction.Commit();
  143. return true;
  144. }
  145. }
  146. }
  147. catch (Exception e)
  148. {
  149. m_log.Error("[NHIBERNATE] issue inserting object ", e);
  150. return false;
  151. }
  152. }
  153. public bool Update(object obj)
  154. {
  155. try
  156. {
  157. using (IStatelessSession session = sessionFactory.OpenStatelessSession())
  158. {
  159. using (ITransaction transaction = session.BeginTransaction())
  160. {
  161. session.Update(obj);
  162. transaction.Commit();
  163. return true;
  164. }
  165. }
  166. }
  167. catch (Exception e)
  168. {
  169. m_log.Error("[NHIBERNATE] issue updating object ", e);
  170. return false;
  171. }
  172. }
  173. public bool Delete(object obj)
  174. {
  175. try
  176. {
  177. using (IStatelessSession session = sessionFactory.OpenStatelessSession())
  178. {
  179. using (ITransaction transaction = session.BeginTransaction())
  180. {
  181. session.Delete(obj);
  182. transaction.Commit();
  183. return true;
  184. }
  185. }
  186. }
  187. catch (Exception e)
  188. {
  189. m_log.Error("[NHIBERNATE] issue deleting object ", e);
  190. return false;
  191. }
  192. }
  193. public void DropSchema()
  194. {
  195. SchemaExport export = new SchemaExport(this.configuration);
  196. export.Drop(true, true);
  197. using (ISession session = sessionFactory.OpenSession())
  198. {
  199. ISQLQuery sqlQuery=session.CreateSQLQuery("drop table migrations");
  200. sqlQuery.ExecuteUpdate();
  201. }
  202. }
  203. public ISession GetSession()
  204. {
  205. return sessionFactory.OpenSession();
  206. }
  207. }
  208. }