PGSQLRegionData.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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 OpenSimulator 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;
  29. using System.Collections.Generic;
  30. using System.Data;
  31. using System.Reflection;
  32. using log4net;
  33. using OpenMetaverse;
  34. using OpenSim.Framework;
  35. using OpenSim.Data;
  36. using RegionFlags = OpenSim.Framework.RegionFlags;
  37. using Npgsql;
  38. namespace OpenSim.Data.PGSQL
  39. {
  40. /// <summary>
  41. /// A PGSQL Interface for the Region Server.
  42. /// </summary>
  43. public class PGSQLRegionData : IRegionData
  44. {
  45. private string m_Realm;
  46. private List<string> m_ColumnNames = null;
  47. private string m_ConnectionString;
  48. private PGSQLManager m_database;
  49. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  50. protected Dictionary<string, string> m_FieldTypes = new Dictionary<string, string>();
  51. protected virtual Assembly Assembly
  52. {
  53. get { return GetType().Assembly; }
  54. }
  55. public PGSQLRegionData(string connectionString, string realm)
  56. {
  57. m_Realm = realm;
  58. m_ConnectionString = connectionString;
  59. m_database = new PGSQLManager(connectionString);
  60. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  61. {
  62. conn.Open();
  63. Migration m = new Migration(conn, GetType().Assembly, "GridStore");
  64. m.Update();
  65. }
  66. LoadFieldTypes();
  67. }
  68. private void LoadFieldTypes()
  69. {
  70. m_FieldTypes = new Dictionary<string, string>();
  71. string query = string.Format(@"select column_name,data_type
  72. from INFORMATION_SCHEMA.COLUMNS
  73. where table_name = lower('{0}');
  74. ", m_Realm);
  75. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  76. using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn))
  77. {
  78. conn.Open();
  79. using (NpgsqlDataReader rdr = cmd.ExecuteReader())
  80. {
  81. while (rdr.Read())
  82. {
  83. // query produces 0 to many rows of single column, so always add the first item in each row
  84. m_FieldTypes.Add((string)rdr[0], (string)rdr[1]);
  85. }
  86. }
  87. }
  88. }
  89. public List<RegionData> Get(string regionName, UUID scopeID)
  90. {
  91. string sql = "select * from "+m_Realm+" where lower(\"regionName\") like lower(:regionName) ";
  92. if (scopeID != UUID.Zero)
  93. sql += " and \"ScopeID\" = :scopeID";
  94. sql += " order by lower(\"regionName\")";
  95. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  96. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  97. {
  98. cmd.Parameters.Add(m_database.CreateParameter("regionName", regionName));
  99. if (scopeID != UUID.Zero)
  100. cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID));
  101. conn.Open();
  102. return RunCommand(cmd);
  103. }
  104. }
  105. public RegionData GetSpecific(string regionName, UUID scopeID)
  106. {
  107. string sql = "select * from " + m_Realm + " where lower(\"regionName\") = lower(:regionName) ";
  108. if (scopeID != UUID.Zero)
  109. sql += " and \"ScopeID\" = :scopeID";
  110. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  111. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  112. {
  113. cmd.Parameters.Add(m_database.CreateParameter("regionName", regionName));
  114. if (scopeID != UUID.Zero)
  115. cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID));
  116. conn.Open();
  117. List<RegionData> ret = RunCommand(cmd);
  118. if (ret.Count == 0)
  119. return null;
  120. return ret[0];
  121. }
  122. }
  123. public RegionData Get(int posX, int posY, UUID scopeID)
  124. {
  125. // extend database search for maximum region size area
  126. string sql = "select * from "+m_Realm+" where \"locX\" between :startX and :endX and \"locY\" between :startY and :endY";
  127. if (scopeID != UUID.Zero)
  128. sql += " and \"ScopeID\" = :scopeID";
  129. int startX = posX - (int)Constants.MaximumRegionSize;
  130. int startY = posY - (int)Constants.MaximumRegionSize;
  131. int endX = posX;
  132. int endY = posY;
  133. List<RegionData> ret;
  134. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  135. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  136. {
  137. cmd.Parameters.Add(m_database.CreateParameter("startX", startX));
  138. cmd.Parameters.Add(m_database.CreateParameter("startY", startY));
  139. cmd.Parameters.Add(m_database.CreateParameter("endX", endX));
  140. cmd.Parameters.Add(m_database.CreateParameter("endY", endY));
  141. if (scopeID != UUID.Zero)
  142. cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID));
  143. conn.Open();
  144. ret = RunCommand(cmd);
  145. }
  146. if (ret.Count == 0)
  147. return null;
  148. // Find the first that contains pos
  149. RegionData rg = null;
  150. foreach (RegionData r in ret)
  151. {
  152. if (posX >= r.posX && posX < r.posX + r.sizeX
  153. && posY >= r.posY && posY < r.posY + r.sizeY)
  154. {
  155. rg = r;
  156. break;
  157. }
  158. }
  159. return rg;
  160. }
  161. public RegionData Get(UUID regionID, UUID scopeID)
  162. {
  163. string sql = "select * from "+m_Realm+" where uuid = :regionID";
  164. if (scopeID != UUID.Zero)
  165. sql += " and \"ScopeID\" = :scopeID";
  166. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  167. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  168. {
  169. cmd.Parameters.Add(m_database.CreateParameter("regionID", regionID));
  170. if (scopeID != UUID.Zero)
  171. cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID));
  172. conn.Open();
  173. List<RegionData> ret = RunCommand(cmd);
  174. if (ret.Count == 0)
  175. return null;
  176. return ret[0];
  177. }
  178. }
  179. public List<RegionData> Get(int startX, int startY, int endX, int endY, UUID scopeID)
  180. {
  181. // extend database search for maximum region size area
  182. string sql = "select * from "+m_Realm+" where \"locX\" between :startX and :endX and \"locY\" between :startY and :endY";
  183. if (scopeID != UUID.Zero)
  184. sql += " and \"ScopeID\" = :scopeID";
  185. int qstartX = startX - (int)Constants.MaximumRegionSize;
  186. int qstartY = startY - (int)Constants.MaximumRegionSize;
  187. List<RegionData> dbret;
  188. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  189. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  190. {
  191. cmd.Parameters.Add(m_database.CreateParameter("startX", qstartX));
  192. cmd.Parameters.Add(m_database.CreateParameter("startY", qstartY));
  193. cmd.Parameters.Add(m_database.CreateParameter("endX", endX));
  194. cmd.Parameters.Add(m_database.CreateParameter("endY", endY));
  195. if (scopeID != UUID.Zero)
  196. cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID));
  197. conn.Open();
  198. dbret = RunCommand(cmd);
  199. }
  200. List<RegionData> ret = new List<RegionData>();
  201. if(dbret.Count == 0)
  202. return ret;
  203. foreach (RegionData r in dbret)
  204. {
  205. if (r.posX + r.sizeX > startX && r.posX <= endX
  206. && r.posY + r.sizeY > startY && r.posY <= endY)
  207. ret.Add(r);
  208. }
  209. return ret;
  210. }
  211. public List<RegionData> RunCommand(NpgsqlCommand cmd)
  212. {
  213. List<RegionData> retList = new List<RegionData>();
  214. NpgsqlDataReader result = cmd.ExecuteReader();
  215. while (result.Read())
  216. {
  217. RegionData ret = new RegionData();
  218. ret.Data = new Dictionary<string, object>();
  219. UUID regionID;
  220. UUID.TryParse(result["uuid"].ToString(), out regionID);
  221. ret.RegionID = regionID;
  222. UUID scope;
  223. UUID.TryParse(result["ScopeID"].ToString(), out scope);
  224. ret.ScopeID = scope;
  225. ret.RegionName = result["regionName"].ToString();
  226. ret.posX = Convert.ToInt32(result["locX"]);
  227. ret.posY = Convert.ToInt32(result["locY"]);
  228. ret.sizeX = Convert.ToInt32(result["sizeX"]);
  229. ret.sizeY = Convert.ToInt32(result["sizeY"]);
  230. if (m_ColumnNames == null)
  231. {
  232. m_ColumnNames = new List<string>();
  233. DataTable schemaTable = result.GetSchemaTable();
  234. foreach (DataRow row in schemaTable.Rows)
  235. m_ColumnNames.Add(row["ColumnName"].ToString());
  236. }
  237. foreach (string s in m_ColumnNames)
  238. {
  239. if (s == "uuid")
  240. continue;
  241. if (s == "ScopeID")
  242. continue;
  243. if (s == "regionName")
  244. continue;
  245. if (s == "locX")
  246. continue;
  247. if (s == "locY")
  248. continue;
  249. ret.Data[s] = result[s].ToString();
  250. }
  251. retList.Add(ret);
  252. }
  253. return retList;
  254. }
  255. public bool Store(RegionData data)
  256. {
  257. if (data.Data.ContainsKey("uuid"))
  258. data.Data.Remove("uuid");
  259. if (data.Data.ContainsKey("ScopeID"))
  260. data.Data.Remove("ScopeID");
  261. if (data.Data.ContainsKey("regionName"))
  262. data.Data.Remove("regionName");
  263. if (data.Data.ContainsKey("posX"))
  264. data.Data.Remove("posX");
  265. if (data.Data.ContainsKey("posY"))
  266. data.Data.Remove("posY");
  267. if (data.Data.ContainsKey("sizeX"))
  268. data.Data.Remove("sizeX");
  269. if (data.Data.ContainsKey("sizeY"))
  270. data.Data.Remove("sizeY");
  271. if (data.Data.ContainsKey("locX"))
  272. data.Data.Remove("locX");
  273. if (data.Data.ContainsKey("locY"))
  274. data.Data.Remove("locY");
  275. string[] fields = new List<string>(data.Data.Keys).ToArray();
  276. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  277. using (NpgsqlCommand cmd = new NpgsqlCommand())
  278. {
  279. string update = "update " + m_Realm + " set \"locX\"=:posX, \"locY\"=:posY, \"sizeX\"=:sizeX, \"sizeY\"=:sizeY ";
  280. foreach (string field in fields)
  281. {
  282. update += ", ";
  283. update += " \"" + field + "\" = :" + field;
  284. if (m_FieldTypes.ContainsKey(field))
  285. cmd.Parameters.Add(m_database.CreateParameter(field, data.Data[field], m_FieldTypes[field]));
  286. else
  287. cmd.Parameters.Add(m_database.CreateParameter(field, data.Data[field]));
  288. }
  289. update += " where uuid = :regionID";
  290. if (data.ScopeID != UUID.Zero)
  291. update += " and \"ScopeID\" = :scopeID";
  292. cmd.CommandText = update;
  293. cmd.Connection = conn;
  294. cmd.Parameters.Add(m_database.CreateParameter("regionID", data.RegionID));
  295. cmd.Parameters.Add(m_database.CreateParameter("regionName", data.RegionName));
  296. cmd.Parameters.Add(m_database.CreateParameter("scopeID", data.ScopeID));
  297. cmd.Parameters.Add(m_database.CreateParameter("posX", data.posX));
  298. cmd.Parameters.Add(m_database.CreateParameter("posY", data.posY));
  299. cmd.Parameters.Add(m_database.CreateParameter("sizeX", data.sizeX));
  300. cmd.Parameters.Add(m_database.CreateParameter("sizeY", data.sizeY));
  301. conn.Open();
  302. try
  303. {
  304. if (cmd.ExecuteNonQuery() < 1)
  305. {
  306. string insert = "insert into " + m_Realm + " (uuid, \"ScopeID\", \"locX\", \"locY\", \"sizeX\", \"sizeY\", \"regionName\", \"" +
  307. String.Join("\", \"", fields) +
  308. "\") values (:regionID, :scopeID, :posX, :posY, :sizeX, :sizeY, :regionName, :" + String.Join(", :", fields) + ")";
  309. cmd.CommandText = insert;
  310. try
  311. {
  312. if (cmd.ExecuteNonQuery() < 1)
  313. {
  314. return false;
  315. }
  316. }
  317. catch (Exception ex)
  318. {
  319. m_log.Warn("[PGSQL Grid]: Error inserting into Regions table: " + ex.Message + ", INSERT sql: " + insert);
  320. }
  321. }
  322. }
  323. catch (Exception ex)
  324. {
  325. m_log.Warn("[PGSQL Grid]: Error updating Regions table: " + ex.Message + ", UPDATE sql: " + update);
  326. }
  327. }
  328. return true;
  329. }
  330. public bool SetDataItem(UUID regionID, string item, string value)
  331. {
  332. string sql = "update " + m_Realm +
  333. " set \"" + item + "\" = :" + item + " where uuid = :UUID";
  334. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  335. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  336. {
  337. cmd.Parameters.Add(m_database.CreateParameter("" + item, value));
  338. cmd.Parameters.Add(m_database.CreateParameter("UUID", regionID));
  339. conn.Open();
  340. if (cmd.ExecuteNonQuery() > 0)
  341. return true;
  342. }
  343. return false;
  344. }
  345. public bool Delete(UUID regionID)
  346. {
  347. string sql = "delete from " + m_Realm +
  348. " where uuid = :UUID";
  349. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  350. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  351. {
  352. cmd.Parameters.Add(m_database.CreateParameter("UUID", regionID));
  353. conn.Open();
  354. if (cmd.ExecuteNonQuery() > 0)
  355. return true;
  356. }
  357. return false;
  358. }
  359. public List<RegionData> GetDefaultRegions(UUID scopeID)
  360. {
  361. return Get((int)RegionFlags.DefaultRegion, scopeID);
  362. }
  363. public List<RegionData> GetDefaultHypergridRegions(UUID scopeID)
  364. {
  365. return Get((int)RegionFlags.DefaultHGRegion, scopeID);
  366. }
  367. public List<RegionData> GetFallbackRegions(UUID scopeID, int x, int y)
  368. {
  369. List<RegionData> regions = Get((int)RegionFlags.FallbackRegion, scopeID);
  370. RegionDataDistanceCompare distanceComparer = new RegionDataDistanceCompare(x, y);
  371. regions.Sort(distanceComparer);
  372. return regions;
  373. }
  374. public List<RegionData> GetHyperlinks(UUID scopeID)
  375. {
  376. return Get((int)RegionFlags.Hyperlink, scopeID);
  377. }
  378. private List<RegionData> Get(int regionFlags, UUID scopeID)
  379. {
  380. string sql = "SELECT * FROM " + m_Realm + " WHERE (\"flags\" & " + regionFlags.ToString() + ") <> 0";
  381. if (scopeID != UUID.Zero)
  382. sql += " AND \"ScopeID\" = :scopeID";
  383. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  384. using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
  385. {
  386. cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID));
  387. conn.Open();
  388. return RunCommand(cmd);
  389. }
  390. }
  391. }
  392. }