MSSQLEstateData.cs 17 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.Reflection;
  32. using OpenMetaverse;
  33. using log4net;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.Environment.Interfaces;
  36. namespace OpenSim.Data.MSSQL
  37. {
  38. public class MSSQLEstateData : IEstateDataStore
  39. {
  40. private const string _migrationStore = "EstateStore";
  41. private static readonly ILog _Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  42. private MSSQLManager _Database;
  43. private FieldInfo[] _Fields;
  44. private Dictionary<string, FieldInfo> _FieldMap = new Dictionary<string, FieldInfo>();
  45. #region Public methods
  46. /// <summary>
  47. /// Initialises the estatedata class.
  48. /// </summary>
  49. /// <param name="connectionString">connectionString.</param>
  50. public void Initialise(string connectionString)
  51. {
  52. if (!string.IsNullOrEmpty(connectionString))
  53. {
  54. _Database = new MSSQLManager(connectionString);
  55. }
  56. else
  57. {
  58. //TODO when can this be deleted
  59. IniFile iniFile = new IniFile("mssql_connection.ini");
  60. string settingDataSource = iniFile.ParseFileReadValue("data_source");
  61. string settingInitialCatalog = iniFile.ParseFileReadValue("initial_catalog");
  62. string settingPersistSecurityInfo = iniFile.ParseFileReadValue("persist_security_info");
  63. string settingUserId = iniFile.ParseFileReadValue("user_id");
  64. string settingPassword = iniFile.ParseFileReadValue("password");
  65. _Database =
  66. new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId,
  67. settingPassword);
  68. }
  69. //Migration settings
  70. _Database.CheckMigration(_migrationStore);
  71. //Interesting way to get parameters! Maybe implement that also with other types
  72. Type t = typeof(EstateSettings);
  73. _Fields = t.GetFields(BindingFlags.NonPublic |
  74. BindingFlags.Instance |
  75. BindingFlags.DeclaredOnly);
  76. foreach (FieldInfo f in _Fields)
  77. {
  78. if (f.Name.Substring(0, 2) == "m_")
  79. _FieldMap[f.Name.Substring(2)] = f;
  80. }
  81. }
  82. /// <summary>
  83. /// Loads the estate settings.
  84. /// </summary>
  85. /// <param name="regionID">region ID.</param>
  86. /// <returns></returns>
  87. public EstateSettings LoadEstateSettings(UUID regionID)
  88. {
  89. EstateSettings es = new EstateSettings();
  90. string sql = "select estate_settings." + String.Join(",estate_settings.", FieldList) + " from estate_map left join estate_settings on estate_map.EstateID = estate_settings.EstateID where estate_settings.EstateID is not null and RegionID = @RegionID";
  91. bool insertEstate = false;
  92. using (AutoClosingSqlCommand cmd = _Database.Query(sql))
  93. {
  94. cmd.Parameters.AddWithValue("@RegionID", regionID.ToString());
  95. using (IDataReader reader = cmd.ExecuteReader())
  96. {
  97. if (reader.Read())
  98. {
  99. foreach (string name in FieldList)
  100. {
  101. if (_FieldMap[name].GetValue(es) is bool)
  102. {
  103. int v = Convert.ToInt32(reader[name]);
  104. if (v != 0)
  105. _FieldMap[name].SetValue(es, true);
  106. else
  107. _FieldMap[name].SetValue(es, false);
  108. }
  109. else if (_FieldMap[name].GetValue(es) is UUID)
  110. {
  111. UUID uuid;
  112. UUID.TryParse(reader[name].ToString(), out uuid);
  113. _FieldMap[name].SetValue(es, uuid);
  114. }
  115. else
  116. {
  117. es.EstateID = Convert.ToUInt32(reader["EstateID"].ToString());
  118. //Problems converting a Int32 to a UInt32
  119. //_FieldMap[name].SetValue(es, reader["EstateID"]);
  120. }
  121. }
  122. }
  123. else
  124. {
  125. insertEstate = true;
  126. }
  127. }
  128. }
  129. if (insertEstate)
  130. {
  131. List<string> names = new List<string>(FieldList);
  132. names.Remove("EstateID");
  133. sql = string.Format("insert into estate_settings ({0}) values ( @{1})", String.Join(",", names.ToArray()), String.Join(", @", names.ToArray()));
  134. //_Log.Debug("[DB ESTATE]: SQL: " + sql);
  135. using (SqlConnection connection = _Database.DatabaseConnection())
  136. {
  137. using (SqlCommand insertCommand = connection.CreateCommand())
  138. {
  139. insertCommand.CommandText = sql + " SET @ID = SCOPE_IDENTITY()";
  140. foreach (string name in names)
  141. {
  142. if (_FieldMap[name].GetValue(es) is bool)
  143. {
  144. SqlParameter tempBool = new SqlParameter("@" + name, SqlDbType.Bit);
  145. if ((bool) _FieldMap[name].GetValue(es))
  146. tempBool.Value = 1;
  147. else
  148. tempBool.Value = 0;
  149. insertCommand.Parameters.Add(tempBool);
  150. }
  151. else
  152. {
  153. //cmd.Parameters.AddWithValue("@" + name, _FieldMap[name].GetValue(es));
  154. SqlParameter tempPar = new SqlParameter("@" + name,
  155. _Database.DbtypeFromType(_FieldMap[name].FieldType));
  156. tempPar.Value = _FieldMap[name].GetValue(es).ToString();
  157. insertCommand.Parameters.Add(tempPar);
  158. }
  159. }
  160. SqlParameter idParameter = new SqlParameter("@ID", SqlDbType.Int);
  161. idParameter.Direction = ParameterDirection.Output;
  162. insertCommand.Parameters.Add(idParameter);
  163. insertCommand.ExecuteNonQuery();
  164. es.EstateID = Convert.ToUInt32(idParameter.Value);
  165. }
  166. }
  167. using (AutoClosingSqlCommand cmd = _Database.Query("INSERT INTO [estate_map] ([RegionID] ,[EstateID]) VALUES (@RegionID, @EstateID)"))
  168. {
  169. cmd.Parameters.Add(_Database.CreateParameter("@RegionID", regionID.ToString()));
  170. cmd.Parameters.Add(_Database.CreateParameter("@EstateID", es.EstateID));
  171. // This will throw on dupe key
  172. try
  173. {
  174. cmd.ExecuteNonQuery();
  175. }
  176. catch (Exception e)
  177. {
  178. _Log.DebugFormat("[ESTATE DB]: Error inserting regionID and EstateID in estate_map: {0}", e);
  179. }
  180. }
  181. // Munge and transfer the ban list
  182. //
  183. sql = string.Format("insert into estateban select {0}, bannedUUID, bannedIp, bannedIpHostMask, '' from regionban where regionban.regionUUID = @UUID", es.EstateID);
  184. using (AutoClosingSqlCommand cmd = _Database.Query(sql))
  185. {
  186. cmd.Parameters.Add(_Database.CreateParameter("@UUID", regionID));
  187. try
  188. {
  189. cmd.ExecuteNonQuery();
  190. }
  191. catch (Exception)
  192. {
  193. _Log.Debug("[ESTATE DB]: Error setting up estateban from regionban");
  194. }
  195. }
  196. //TODO check if this is needed??
  197. es.Save();
  198. }
  199. LoadBanList(es);
  200. es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
  201. es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users");
  202. es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups");
  203. //Set event
  204. es.OnSave += StoreEstateSettings;
  205. return es;
  206. }
  207. /// <summary>
  208. /// Stores the estate settings.
  209. /// </summary>
  210. /// <param name="es">estate settings</param>
  211. public void StoreEstateSettings(EstateSettings es)
  212. {
  213. List<string> names = new List<string>(FieldList);
  214. names.Remove("EstateID");
  215. string sql = string.Format("UPDATE estate_settings SET ") ; // ({0}) values ( @{1}) WHERE EstateID = @EstateID", String.Join(",", names.ToArray()), String.Join(", @", names.ToArray()));
  216. foreach (string name in names)
  217. {
  218. sql += name + " = @" + name + ", ";
  219. }
  220. sql = sql.Remove(sql.LastIndexOf(","));
  221. sql += " WHERE EstateID = @EstateID";
  222. using (AutoClosingSqlCommand cmd = _Database.Query(sql))
  223. {
  224. foreach (string name in names)
  225. {
  226. if (_FieldMap[name].GetValue(es) is bool)
  227. {
  228. SqlParameter tempBool = new SqlParameter("@" + name, SqlDbType.Bit);
  229. if ((bool)_FieldMap[name].GetValue(es))
  230. tempBool.Value = 1;
  231. else
  232. tempBool.Value = 0;
  233. cmd.Parameters.Add(tempBool);
  234. }
  235. else
  236. {
  237. //cmd.Parameters.AddWithValue("@" + name, _FieldMap[name].GetValue(es));
  238. SqlParameter tempPar = new SqlParameter("@" + name,
  239. _Database.DbtypeFromType(_FieldMap[name].FieldType));
  240. tempPar.Value = _FieldMap[name].GetValue(es).ToString();
  241. cmd.Parameters.Add(tempPar);
  242. }
  243. }
  244. SqlParameter idParameter = new SqlParameter("@EstateID", SqlDbType.Int);
  245. idParameter.Value = es.EstateID;
  246. cmd.Parameters.Add(idParameter);
  247. cmd.ExecuteNonQuery();
  248. }
  249. SaveBanList(es);
  250. SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers);
  251. SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess);
  252. SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups);
  253. }
  254. #endregion
  255. #region Private methods
  256. private string[] FieldList
  257. {
  258. get { return new List<string>(_FieldMap.Keys).ToArray(); }
  259. }
  260. private void LoadBanList(EstateSettings es)
  261. {
  262. es.ClearBans();
  263. string sql = "select bannedUUID from estateban where EstateID = @EstateID";
  264. using (AutoClosingSqlCommand cmd = _Database.Query(sql))
  265. {
  266. SqlParameter idParameter = new SqlParameter("@EstateID", SqlDbType.Int);
  267. idParameter.Value = es.EstateID;
  268. cmd.Parameters.Add(idParameter);
  269. using (IDataReader reader = cmd.ExecuteReader())
  270. {
  271. while (reader.Read())
  272. {
  273. EstateBan eb = new EstateBan();
  274. UUID uuid;
  275. UUID.TryParse(reader["bannedUUID"].ToString(), out uuid);
  276. eb.bannedUUID = uuid;
  277. eb.bannedIP = "0.0.0.0";
  278. eb.bannedIPHostMask = "0.0.0.0";
  279. es.AddBan(eb);
  280. }
  281. }
  282. }
  283. }
  284. private UUID[] LoadUUIDList(uint estateID, string table)
  285. {
  286. List<UUID> uuids = new List<UUID>();
  287. string sql = string.Format("select uuid from {0} where EstateID = @EstateID", table);
  288. using (AutoClosingSqlCommand cmd = _Database.Query(sql))
  289. {
  290. cmd.Parameters.Add(_Database.CreateParameter("@EstateID", estateID));
  291. using (IDataReader reader = cmd.ExecuteReader())
  292. {
  293. while (reader.Read())
  294. {
  295. // EstateBan eb = new EstateBan();
  296. UUID uuid;
  297. UUID.TryParse(reader["uuid"].ToString(), out uuid);
  298. uuids.Add(uuid);
  299. }
  300. }
  301. }
  302. return uuids.ToArray();
  303. }
  304. private void SaveBanList(EstateSettings es)
  305. {
  306. //Delete first
  307. string sql = "delete from estateban where EstateID = @EstateID";
  308. using (AutoClosingSqlCommand cmd = _Database.Query(sql))
  309. {
  310. cmd.Parameters.Add(_Database.CreateParameter("@EstateID", es.EstateID));
  311. cmd.ExecuteNonQuery();
  312. }
  313. //Insert after
  314. sql = "insert into estateban (EstateID, bannedUUID) values ( @EstateID, @bannedUUID )";
  315. using (AutoClosingSqlCommand cmd = _Database.Query(sql))
  316. {
  317. foreach (EstateBan b in es.EstateBans)
  318. {
  319. cmd.Parameters.Add(_Database.CreateParameter("@EstateID", es.EstateID));
  320. cmd.Parameters.Add(_Database.CreateParameter("@bannedUUID", b.bannedUUID));
  321. cmd.ExecuteNonQuery();
  322. cmd.Parameters.Clear();
  323. }
  324. }
  325. }
  326. private void SaveUUIDList(uint estateID, string table, UUID[] data)
  327. {
  328. //Delete first
  329. string sql = string.Format("delete from {0} where EstateID = @EstateID", table);
  330. using (AutoClosingSqlCommand cmd = _Database.Query(sql))
  331. {
  332. cmd.Parameters.Add(_Database.CreateParameter("@EstateID", estateID));
  333. cmd.ExecuteNonQuery();
  334. }
  335. sql = string.Format("insert into {0} (EstateID, uuid) values ( @EstateID, @uuid )", table);
  336. using (AutoClosingSqlCommand cmd = _Database.Query(sql))
  337. {
  338. cmd.Parameters.Add(_Database.CreateParameter("@EstateID", estateID));
  339. bool createParamOnce = true;
  340. foreach (UUID uuid in data)
  341. {
  342. if (createParamOnce)
  343. {
  344. cmd.Parameters.Add(_Database.CreateParameter("@uuid", uuid));
  345. createParamOnce = false;
  346. }
  347. else
  348. cmd.Parameters["@uuid"].Value = uuid.ToString();
  349. cmd.ExecuteNonQuery();
  350. }
  351. }
  352. }
  353. #endregion
  354. }
  355. }