MySQLDataStore.cs 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799
  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.IO;
  31. using System.Reflection;
  32. using System.Threading;
  33. using libsecondlife;
  34. using log4net;
  35. using MySql.Data.MySqlClient;
  36. using OpenSim.Framework;
  37. using OpenSim.Region.Environment.Interfaces;
  38. using OpenSim.Region.Environment.Scenes;
  39. namespace OpenSim.Data.MySQL
  40. {
  41. public class MySQLDataStore : IRegionDataStore
  42. {
  43. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  44. private const string m_primSelect = "select * from prims";
  45. private const string m_shapeSelect = "select * from primshapes";
  46. private const string m_itemsSelect = "select * from primitems";
  47. private const string m_terrainSelect = "select * from terrain limit 1";
  48. private const string m_landSelect = "select * from land";
  49. private const string m_landAccessListSelect = "select * from landaccesslist";
  50. /// <summary>
  51. /// We're only using this to version the table!
  52. /// </summary>
  53. private DataSet m_dataSet;
  54. private MySqlDataAdapter m_primDataAdapter;
  55. private MySqlDataAdapter m_shapeDataAdapter;
  56. private MySqlDataAdapter m_itemsDataAdapter;
  57. private MySqlConnection m_connection;
  58. private MySqlDataAdapter m_terrainDataAdapter;
  59. private MySqlDataAdapter m_landDataAdapter;
  60. private MySqlDataAdapter m_landAccessListDataAdapter;
  61. private DataTable m_primTable;
  62. private DataTable m_shapeTable;
  63. private DataTable m_itemsTable;
  64. private DataTable m_terrainTable;
  65. private DataTable m_landTable;
  66. private DataTable m_landAccessListTable;
  67. // Temporary attribute while this is experimental
  68. private bool persistPrimInventories;
  69. /***********************************************************************
  70. *
  71. * Public Interface Functions
  72. *
  73. **********************************************************************/
  74. // see IRegionDataStore
  75. public void Initialise(string connectionstring, bool persistPrimInventories)
  76. {
  77. m_dataSet = new DataSet();
  78. this.persistPrimInventories = persistPrimInventories;
  79. m_log.Info("[REGION DB]: MySql - connecting: " + connectionstring);
  80. m_connection = new MySqlConnection(connectionstring);
  81. TestTablesVersionable(m_connection);
  82. MySqlCommand primSelectCmd = new MySqlCommand(m_primSelect, m_connection);
  83. m_primDataAdapter = new MySqlDataAdapter(primSelectCmd);
  84. MySqlCommand shapeSelectCmd = new MySqlCommand(m_shapeSelect, m_connection);
  85. m_shapeDataAdapter = new MySqlDataAdapter(shapeSelectCmd);
  86. MySqlCommand itemsSelectCmd = new MySqlCommand(m_itemsSelect, m_connection);
  87. m_itemsDataAdapter = new MySqlDataAdapter(itemsSelectCmd);
  88. MySqlCommand terrainSelectCmd = new MySqlCommand(m_terrainSelect, m_connection);
  89. m_terrainDataAdapter = new MySqlDataAdapter(terrainSelectCmd);
  90. MySqlCommand landSelectCmd = new MySqlCommand(m_landSelect, m_connection);
  91. m_landDataAdapter = new MySqlDataAdapter(landSelectCmd);
  92. MySqlCommand landAccessListSelectCmd = new MySqlCommand(m_landAccessListSelect, m_connection);
  93. m_landAccessListDataAdapter = new MySqlDataAdapter(landAccessListSelectCmd);
  94. TestTables(m_connection);
  95. lock (m_dataSet)
  96. {
  97. m_primTable = createPrimTable();
  98. m_dataSet.Tables.Add(m_primTable);
  99. SetupPrimCommands(m_primDataAdapter, m_connection);
  100. m_primDataAdapter.Fill(m_primTable);
  101. m_shapeTable = createShapeTable();
  102. m_dataSet.Tables.Add(m_shapeTable);
  103. SetupShapeCommands(m_shapeDataAdapter, m_connection);
  104. m_shapeDataAdapter.Fill(m_shapeTable);
  105. if (persistPrimInventories)
  106. {
  107. m_itemsTable = createItemsTable();
  108. m_dataSet.Tables.Add(m_itemsTable);
  109. SetupItemsCommands(m_itemsDataAdapter, m_connection);
  110. m_itemsDataAdapter.Fill(m_itemsTable);
  111. }
  112. m_terrainTable = createTerrainTable();
  113. m_dataSet.Tables.Add(m_terrainTable);
  114. SetupTerrainCommands(m_terrainDataAdapter, m_connection);
  115. m_terrainDataAdapter.Fill(m_terrainTable);
  116. m_landTable = createLandTable();
  117. m_dataSet.Tables.Add(m_landTable);
  118. setupLandCommands(m_landDataAdapter, m_connection);
  119. m_landDataAdapter.Fill(m_landTable);
  120. m_landAccessListTable = createLandAccessListTable();
  121. m_dataSet.Tables.Add(m_landAccessListTable);
  122. setupLandAccessCommands(m_landAccessListDataAdapter, m_connection);
  123. m_landAccessListDataAdapter.Fill(m_landAccessListTable);
  124. }
  125. }
  126. /// <summary>
  127. /// Given a list of tables, return the version of the tables, as seen in the database
  128. /// </summary>
  129. /// <param name="tableList"></param>
  130. public void GetTableVersion(Dictionary<string, string> tableList, MySqlConnection dbcon)
  131. {
  132. lock (dbcon)
  133. {
  134. MySqlCommand tablesCmd =
  135. new MySqlCommand(
  136. "SELECT TABLE_NAME, TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=?dbname",
  137. dbcon);
  138. tablesCmd.Parameters.AddWithValue("?dbname", dbcon.Database);
  139. using (MySqlDataReader tables = tablesCmd.ExecuteReader())
  140. {
  141. while (tables.Read())
  142. {
  143. try
  144. {
  145. string tableName = (string)tables["TABLE_NAME"];
  146. string comment = (string)tables["TABLE_COMMENT"];
  147. if (tableList.ContainsKey(tableName))
  148. {
  149. tableList[tableName] = comment;
  150. }
  151. }
  152. catch (Exception e)
  153. {
  154. m_log.Error(e.ToString());
  155. }
  156. }
  157. tables.Close();
  158. }
  159. }
  160. }
  161. private void TestTablesVersionable(MySqlConnection dbconn)
  162. {
  163. Dictionary<string, string> tableList = new Dictionary<string, string>();
  164. tableList["land"] = null;
  165. dbconn.Open();
  166. GetTableVersion(tableList,dbconn);
  167. UpgradeLandTable(tableList["land"], dbconn);
  168. //database.Close();
  169. }
  170. /// <summary>
  171. /// Execute a SQL statement stored in a resource, as a string
  172. /// </summary>
  173. /// <param name="name"></param>
  174. public void ExecuteResourceSql(string name, MySqlConnection dbcon)
  175. {
  176. MySqlCommand cmd = new MySqlCommand(getResourceString(name), dbcon);
  177. cmd.ExecuteNonQuery();
  178. }
  179. /// <summary>
  180. /// Extract a named string resource from the embedded resources
  181. /// </summary>
  182. /// <param name="name">name of embedded resource</param>
  183. /// <returns>string contained within the embedded resource</returns>
  184. private string getResourceString(string name)
  185. {
  186. Assembly assem = GetType().Assembly;
  187. string[] names = assem.GetManifestResourceNames();
  188. foreach (string s in names)
  189. {
  190. if (s.EndsWith(name))
  191. {
  192. using (Stream resource = assem.GetManifestResourceStream(s))
  193. {
  194. using (StreamReader resourceReader = new StreamReader(resource))
  195. {
  196. string resourceString = resourceReader.ReadToEnd();
  197. return resourceString;
  198. }
  199. }
  200. }
  201. }
  202. throw new Exception(string.Format("Resource '{0}' was not found", name));
  203. }
  204. private void UpgradeLandTable(string oldVersion, MySqlConnection dbconn)
  205. {
  206. // null as the version, indicates that the table didn't exist
  207. if (oldVersion == null)
  208. {
  209. ExecuteResourceSql("CreateLandTable.sql",dbconn);
  210. oldVersion = "Rev. 2; InnoDB free: 0 kB";
  211. }
  212. if (!oldVersion.Contains("Rev."))
  213. {
  214. ExecuteResourceSql("UpgradeLandTableToVersion2.sql", dbconn);
  215. }
  216. }
  217. public void StoreObject(SceneObjectGroup obj, LLUUID regionUUID)
  218. {
  219. lock (m_dataSet)
  220. {
  221. foreach (SceneObjectPart prim in obj.Children.Values)
  222. {
  223. if ((prim.GetEffectiveObjectFlags() & (uint) LLObject.ObjectFlags.Physics) == 0)
  224. {
  225. m_log.Info("[REGION DB]: Adding obj: " + obj.UUID + " to region: " + regionUUID);
  226. addPrim(prim, obj.UUID, regionUUID);
  227. }
  228. else
  229. {
  230. // m_log.Info("[DATASTORE]: Ignoring Physical obj: " + obj.UUID + " in region: " + regionUUID);
  231. }
  232. }
  233. Commit();
  234. }
  235. }
  236. public void RemoveObject(LLUUID obj, LLUUID regionUUID)
  237. {
  238. m_log.InfoFormat("[REGION DB]: Removing obj: {0} from region: {1}", obj.UUID, regionUUID);
  239. DataTable prims = m_primTable;
  240. DataTable shapes = m_shapeTable;
  241. string selectExp = "SceneGroupID = '" + Util.ToRawUuidString(obj) + "'";
  242. lock (m_dataSet)
  243. {
  244. DataRow[] primRows = prims.Select(selectExp);
  245. foreach (DataRow row in primRows)
  246. {
  247. // Remove shapes row
  248. LLUUID uuid = new LLUUID((string) row["UUID"]);
  249. DataRow shapeRow = shapes.Rows.Find(Util.ToRawUuidString(uuid));
  250. if (shapeRow != null)
  251. {
  252. shapeRow.Delete();
  253. }
  254. if (persistPrimInventories)
  255. {
  256. RemoveItems(uuid);
  257. }
  258. // Remove prim row
  259. row.Delete();
  260. }
  261. Commit();
  262. }
  263. }
  264. /// <summary>
  265. /// Remove all persisted items of the given prim.
  266. /// The caller must acquire the necessrary synchronization locks and commit or rollback changes.
  267. /// </summary>
  268. private void RemoveItems(LLUUID uuid)
  269. {
  270. String sql = String.Format("primID = '{0}'", uuid);
  271. DataRow[] itemRows = m_itemsTable.Select(sql);
  272. foreach (DataRow itemRow in itemRows)
  273. {
  274. itemRow.Delete();
  275. }
  276. }
  277. /// <summary>
  278. /// Load persisted objects from region storage.
  279. /// </summary>
  280. public List<SceneObjectGroup> LoadObjects(LLUUID regionUUID)
  281. {
  282. Dictionary<LLUUID, SceneObjectGroup> createdObjects = new Dictionary<LLUUID, SceneObjectGroup>();
  283. List<SceneObjectGroup> retvals = new List<SceneObjectGroup>();
  284. DataTable prims = m_primTable;
  285. DataTable shapes = m_shapeTable;
  286. string byRegion = "RegionUUID = '" + Util.ToRawUuidString(regionUUID) + "'";
  287. string orderByParent = "ParentID ASC";
  288. lock (m_dataSet)
  289. {
  290. DataRow[] primsForRegion = prims.Select(byRegion, orderByParent);
  291. m_log.Info("[REGION DB]: " +
  292. "Loaded " + primsForRegion.Length + " prims for region: " + regionUUID);
  293. foreach (DataRow primRow in primsForRegion)
  294. {
  295. try
  296. {
  297. string uuid = (string) primRow["UUID"];
  298. string objID = (string) primRow["SceneGroupID"];
  299. SceneObjectPart prim = buildPrim(primRow);
  300. if (uuid == objID) //is new SceneObjectGroup ?
  301. {
  302. SceneObjectGroup group = new SceneObjectGroup();
  303. DataRow shapeRow = shapes.Rows.Find(Util.ToRawUuidString(prim.UUID));
  304. if (shapeRow != null)
  305. {
  306. prim.Shape = buildShape(shapeRow);
  307. }
  308. else
  309. {
  310. m_log.Info(
  311. "No shape found for prim in storage, so setting default box shape");
  312. prim.Shape = PrimitiveBaseShape.Default;
  313. }
  314. group.AddPart(prim);
  315. group.RootPart = prim;
  316. createdObjects.Add(group.UUID, group);
  317. retvals.Add(group);
  318. }
  319. else
  320. {
  321. DataRow shapeRow = shapes.Rows.Find(Util.ToRawUuidString(prim.UUID));
  322. if (shapeRow != null)
  323. {
  324. prim.Shape = buildShape(shapeRow);
  325. }
  326. else
  327. {
  328. m_log.Info(
  329. "No shape found for prim in storage, so setting default box shape");
  330. prim.Shape = PrimitiveBaseShape.Default;
  331. }
  332. createdObjects[new LLUUID(objID)].AddPart(prim);
  333. }
  334. if (persistPrimInventories)
  335. {
  336. LoadItems(prim);
  337. }
  338. }
  339. catch (Exception e)
  340. {
  341. m_log.Error("[REGION DB]: Failed create prim object, exception and data follows");
  342. m_log.Info("[REGION DB]: " + e.ToString());
  343. foreach (DataColumn col in prims.Columns)
  344. {
  345. m_log.Info("[REGION DB]: Col: " + col.ColumnName + " => " + primRow[col]);
  346. }
  347. }
  348. }
  349. }
  350. return retvals;
  351. }
  352. /// <summary>
  353. /// Load in a prim's persisted inventory.
  354. /// </summary>
  355. /// <param name="prim"></param>
  356. private void LoadItems(SceneObjectPart prim)
  357. {
  358. //m_log.InfoFormat("[DATASTORE]: Loading inventory for {0}, {1}", prim.Name, prim.UUID);
  359. DataTable dbItems = m_itemsTable;
  360. String sql = String.Format("primID = '{0}'", prim.UUID.ToString());
  361. DataRow[] dbItemRows = dbItems.Select(sql);
  362. IList<TaskInventoryItem> inventory = new List<TaskInventoryItem>();
  363. foreach (DataRow row in dbItemRows)
  364. {
  365. TaskInventoryItem item = buildItem(row);
  366. inventory.Add(item);
  367. //m_log.DebugFormat("[DATASTORE]: Restored item {0}, {1}", item.Name, item.ItemID);
  368. }
  369. prim.RestoreInventoryItems(inventory);
  370. // XXX A nasty little hack to recover the folder id for the prim (which is currently stored in
  371. // every item). This data should really be stored in the prim table itself.
  372. if (dbItemRows.Length > 0)
  373. {
  374. prim.FolderID = inventory[0].ParentID;
  375. }
  376. }
  377. public void StoreTerrain(double[,] ter, LLUUID regionID)
  378. {
  379. int revision = Util.UnixTimeSinceEpoch();
  380. m_log.Info("[REGION DB]: Storing terrain revision r" + revision.ToString());
  381. DataTable terrain = m_dataSet.Tables["terrain"];
  382. lock (m_dataSet)
  383. {
  384. MySqlCommand cmd = new MySqlCommand("insert into terrain(RegionUUID, Revision, Heightfield)" +
  385. " values(?RegionUUID, ?Revision, ?Heightfield)", m_connection);
  386. using (cmd)
  387. {
  388. cmd.Parameters.Add(new MySqlParameter("?RegionUUID", Util.ToRawUuidString(regionID)));
  389. cmd.Parameters.Add(new MySqlParameter("?Revision", revision));
  390. cmd.Parameters.Add(new MySqlParameter("?Heightfield", serializeTerrain(ter)));
  391. cmd.ExecuteNonQuery();
  392. }
  393. }
  394. }
  395. public double[,] LoadTerrain(LLUUID regionID)
  396. {
  397. double[,] terret = new double[256,256];
  398. terret.Initialize();
  399. MySqlCommand cmd = new MySqlCommand(
  400. @"select RegionUUID, Revision, Heightfield from terrain
  401. where RegionUUID=?RegionUUID order by Revision desc limit 1"
  402. , m_connection);
  403. MySqlParameter param = new MySqlParameter();
  404. cmd.Parameters.Add(new MySqlParameter("?RegionUUID", Util.ToRawUuidString(regionID)));
  405. if (m_connection.State != ConnectionState.Open)
  406. {
  407. m_connection.Open();
  408. }
  409. lock (m_dataSet)
  410. {
  411. using (MySqlDataReader row = cmd.ExecuteReader())
  412. {
  413. int rev = 0;
  414. if (row.Read())
  415. {
  416. MemoryStream str = new MemoryStream((byte[]) row["Heightfield"]);
  417. BinaryReader br = new BinaryReader(str);
  418. for (int x = 0; x < 256; x++)
  419. {
  420. for (int y = 0; y < 256; y++)
  421. {
  422. terret[x, y] = br.ReadDouble();
  423. }
  424. }
  425. rev = (int) row["Revision"];
  426. }
  427. else
  428. {
  429. m_log.Info("[REGION DB]: No terrain found for region");
  430. return null;
  431. }
  432. m_log.Info("[REGION DB]: Loaded terrain revision r" + rev.ToString());
  433. }
  434. }
  435. return terret;
  436. }
  437. public void RemoveLandObject(LLUUID globalID)
  438. {
  439. lock (m_dataSet)
  440. {
  441. using (MySqlCommand cmd = new MySqlCommand("delete from land where UUID=?UUID", m_connection))
  442. {
  443. cmd.Parameters.Add(new MySqlParameter("?UUID", Util.ToRawUuidString(globalID)));
  444. cmd.ExecuteNonQuery();
  445. }
  446. using (
  447. MySqlCommand cmd = new MySqlCommand("delete from landaccesslist where LandUUID=?UUID", m_connection)
  448. )
  449. {
  450. cmd.Parameters.Add(new MySqlParameter("?UUID", Util.ToRawUuidString(globalID)));
  451. cmd.ExecuteNonQuery();
  452. }
  453. }
  454. }
  455. public void StoreLandObject(ILandObject parcel)
  456. {
  457. lock (m_dataSet)
  458. {
  459. DataTable land = m_landTable;
  460. DataTable landaccesslist = m_landAccessListTable;
  461. DataRow landRow = land.Rows.Find(Util.ToRawUuidString(parcel.landData.globalID));
  462. if (landRow == null)
  463. {
  464. landRow = land.NewRow();
  465. fillLandRow(landRow, parcel.landData, parcel.regionUUID);
  466. land.Rows.Add(landRow);
  467. }
  468. else
  469. {
  470. fillLandRow(landRow, parcel.landData, parcel.regionUUID);
  471. }
  472. using (
  473. MySqlCommand cmd =
  474. new MySqlCommand("delete from landaccesslist where LandUUID=?LandUUID", m_connection))
  475. {
  476. cmd.Parameters.Add(new MySqlParameter("?LandUUID", Util.ToRawUuidString(parcel.landData.globalID)));
  477. cmd.ExecuteNonQuery();
  478. }
  479. foreach (ParcelManager.ParcelAccessEntry entry in parcel.landData.parcelAccessList)
  480. {
  481. DataRow newAccessRow = landaccesslist.NewRow();
  482. fillLandAccessRow(newAccessRow, entry, parcel.landData.globalID);
  483. landaccesslist.Rows.Add(newAccessRow);
  484. }
  485. Commit();
  486. }
  487. }
  488. public List<LandData> LoadLandObjects(LLUUID regionUUID)
  489. {
  490. List<LandData> landDataForRegion = new List<LandData>();
  491. lock (m_dataSet)
  492. {
  493. DataTable land = m_landTable;
  494. DataTable landaccesslist = m_landAccessListTable;
  495. string searchExp = "RegionUUID = '" + Util.ToRawUuidString(regionUUID) + "'";
  496. DataRow[] rawDataForRegion = land.Select(searchExp);
  497. foreach (DataRow rawDataLand in rawDataForRegion)
  498. {
  499. LandData newLand = buildLandData(rawDataLand);
  500. string accessListSearchExp = "LandUUID = '" + Util.ToRawUuidString(newLand.globalID) + "'";
  501. DataRow[] rawDataForLandAccessList = landaccesslist.Select(accessListSearchExp);
  502. foreach (DataRow rawDataLandAccess in rawDataForLandAccessList)
  503. {
  504. newLand.parcelAccessList.Add(buildLandAccessData(rawDataLandAccess));
  505. }
  506. landDataForRegion.Add(newLand);
  507. }
  508. }
  509. return landDataForRegion;
  510. }
  511. public void Commit()
  512. {
  513. if (m_connection.State != ConnectionState.Open)
  514. {
  515. m_connection.Open();
  516. }
  517. lock (m_dataSet)
  518. {
  519. // DisplayDataSet(m_dataSet, "Region DataSet");
  520. m_primDataAdapter.Update(m_primTable);
  521. m_shapeDataAdapter.Update(m_shapeTable);
  522. if (persistPrimInventories)
  523. {
  524. m_itemsDataAdapter.Update(m_itemsTable);
  525. }
  526. m_terrainDataAdapter.Update(m_terrainTable);
  527. m_landDataAdapter.Update(m_landTable);
  528. m_landAccessListDataAdapter.Update(m_landAccessListTable);
  529. m_dataSet.AcceptChanges();
  530. }
  531. }
  532. public void Shutdown()
  533. {
  534. Commit();
  535. }
  536. /***********************************************************************
  537. *
  538. * Database Definition Functions
  539. *
  540. * This should be db agnostic as we define them in ADO.NET terms
  541. *
  542. **********************************************************************/
  543. private static DataColumn createCol(DataTable dt, string name, Type type)
  544. {
  545. DataColumn col = new DataColumn(name, type);
  546. dt.Columns.Add(col);
  547. return col;
  548. }
  549. private static DataTable createTerrainTable()
  550. {
  551. DataTable terrain = new DataTable("terrain");
  552. createCol(terrain, "RegionUUID", typeof (String));
  553. createCol(terrain, "Revision", typeof (Int32));
  554. createCol(terrain, "Heightfield", typeof (Byte[]));
  555. return terrain;
  556. }
  557. private static DataTable createPrimTable()
  558. {
  559. DataTable prims = new DataTable("prims");
  560. createCol(prims, "UUID", typeof (String));
  561. createCol(prims, "RegionUUID", typeof (String));
  562. createCol(prims, "ParentID", typeof (Int32));
  563. createCol(prims, "CreationDate", typeof (Int32));
  564. createCol(prims, "Name", typeof (String));
  565. createCol(prims, "SceneGroupID", typeof (String));
  566. // various text fields
  567. createCol(prims, "Text", typeof (String));
  568. createCol(prims, "Description", typeof (String));
  569. createCol(prims, "SitName", typeof (String));
  570. createCol(prims, "TouchName", typeof (String));
  571. // permissions
  572. createCol(prims, "ObjectFlags", typeof (Int32));
  573. createCol(prims, "CreatorID", typeof (String));
  574. createCol(prims, "OwnerID", typeof (String));
  575. createCol(prims, "GroupID", typeof (String));
  576. createCol(prims, "LastOwnerID", typeof (String));
  577. createCol(prims, "OwnerMask", typeof (Int32));
  578. createCol(prims, "NextOwnerMask", typeof (Int32));
  579. createCol(prims, "GroupMask", typeof (Int32));
  580. createCol(prims, "EveryoneMask", typeof (Int32));
  581. createCol(prims, "BaseMask", typeof (Int32));
  582. // vectors
  583. createCol(prims, "PositionX", typeof (Double));
  584. createCol(prims, "PositionY", typeof (Double));
  585. createCol(prims, "PositionZ", typeof (Double));
  586. createCol(prims, "GroupPositionX", typeof (Double));
  587. createCol(prims, "GroupPositionY", typeof (Double));
  588. createCol(prims, "GroupPositionZ", typeof (Double));
  589. createCol(prims, "VelocityX", typeof (Double));
  590. createCol(prims, "VelocityY", typeof (Double));
  591. createCol(prims, "VelocityZ", typeof (Double));
  592. createCol(prims, "AngularVelocityX", typeof (Double));
  593. createCol(prims, "AngularVelocityY", typeof (Double));
  594. createCol(prims, "AngularVelocityZ", typeof (Double));
  595. createCol(prims, "AccelerationX", typeof (Double));
  596. createCol(prims, "AccelerationY", typeof (Double));
  597. createCol(prims, "AccelerationZ", typeof (Double));
  598. // quaternions
  599. createCol(prims, "RotationX", typeof (Double));
  600. createCol(prims, "RotationY", typeof (Double));
  601. createCol(prims, "RotationZ", typeof (Double));
  602. createCol(prims, "RotationW", typeof (Double));
  603. // sit target
  604. createCol(prims, "SitTargetOffsetX", typeof (Double));
  605. createCol(prims, "SitTargetOffsetY", typeof (Double));
  606. createCol(prims, "SitTargetOffsetZ", typeof (Double));
  607. createCol(prims, "SitTargetOrientW", typeof (Double));
  608. createCol(prims, "SitTargetOrientX", typeof (Double));
  609. createCol(prims, "SitTargetOrientY", typeof (Double));
  610. createCol(prims, "SitTargetOrientZ", typeof (Double));
  611. // Add in contraints
  612. prims.PrimaryKey = new DataColumn[] {prims.Columns["UUID"]};
  613. return prims;
  614. }
  615. private static DataTable createLandTable()
  616. {
  617. DataTable land = new DataTable("land");
  618. createCol(land, "UUID", typeof (String));
  619. createCol(land, "RegionUUID", typeof (String));
  620. createCol(land, "LocalLandID", typeof (Int32));
  621. // Bitmap is a byte[512]
  622. createCol(land, "Bitmap", typeof (Byte[]));
  623. createCol(land, "Name", typeof (String));
  624. createCol(land, "Description", typeof (String));
  625. createCol(land, "OwnerUUID", typeof (String));
  626. createCol(land, "IsGroupOwned", typeof (Int32));
  627. createCol(land, "Area", typeof (Int32));
  628. createCol(land, "AuctionID", typeof (Int32)); //Unemplemented
  629. createCol(land, "Category", typeof (Int32)); //Enum libsecondlife.Parcel.ParcelCategory
  630. createCol(land, "ClaimDate", typeof (Int32));
  631. createCol(land, "ClaimPrice", typeof (Int32));
  632. createCol(land, "GroupUUID", typeof (String));
  633. createCol(land, "SalePrice", typeof (Int32));
  634. createCol(land, "LandStatus", typeof (Int32)); //Enum. libsecondlife.Parcel.ParcelStatus
  635. createCol(land, "LandFlags", typeof (Int32));
  636. createCol(land, "LandingType", typeof (Int32));
  637. createCol(land, "MediaAutoScale", typeof (Int32));
  638. createCol(land, "MediaTextureUUID", typeof (String));
  639. createCol(land, "MediaURL", typeof (String));
  640. createCol(land, "MusicURL", typeof (String));
  641. createCol(land, "PassHours", typeof (Double));
  642. createCol(land, "PassPrice", typeof (Int32));
  643. createCol(land, "SnapshotUUID", typeof (String));
  644. createCol(land, "UserLocationX", typeof (Double));
  645. createCol(land, "UserLocationY", typeof (Double));
  646. createCol(land, "UserLocationZ", typeof (Double));
  647. createCol(land, "UserLookAtX", typeof (Double));
  648. createCol(land, "UserLookAtY", typeof (Double));
  649. createCol(land, "UserLookAtZ", typeof (Double));
  650. createCol(land, "AuthBuyerID", typeof (String));
  651. land.PrimaryKey = new DataColumn[] {land.Columns["UUID"]};
  652. return land;
  653. }
  654. private static DataTable createLandAccessListTable()
  655. {
  656. DataTable landaccess = new DataTable("landaccesslist");
  657. createCol(landaccess, "LandUUID", typeof (String));
  658. createCol(landaccess, "AccessUUID", typeof (String));
  659. createCol(landaccess, "Flags", typeof (Int32));
  660. return landaccess;
  661. }
  662. private static DataTable createShapeTable()
  663. {
  664. DataTable shapes = new DataTable("primshapes");
  665. createCol(shapes, "UUID", typeof (String));
  666. // shape is an enum
  667. createCol(shapes, "Shape", typeof (Int32));
  668. // vectors
  669. createCol(shapes, "ScaleX", typeof (Double));
  670. createCol(shapes, "ScaleY", typeof (Double));
  671. createCol(shapes, "ScaleZ", typeof (Double));
  672. // paths
  673. createCol(shapes, "PCode", typeof (Int32));
  674. createCol(shapes, "PathBegin", typeof (Int32));
  675. createCol(shapes, "PathEnd", typeof (Int32));
  676. createCol(shapes, "PathScaleX", typeof (Int32));
  677. createCol(shapes, "PathScaleY", typeof (Int32));
  678. createCol(shapes, "PathShearX", typeof (Int32));
  679. createCol(shapes, "PathShearY", typeof (Int32));
  680. createCol(shapes, "PathSkew", typeof (Int32));
  681. createCol(shapes, "PathCurve", typeof (Int32));
  682. createCol(shapes, "PathRadiusOffset", typeof (Int32));
  683. createCol(shapes, "PathRevolutions", typeof (Int32));
  684. createCol(shapes, "PathTaperX", typeof (Int32));
  685. createCol(shapes, "PathTaperY", typeof (Int32));
  686. createCol(shapes, "PathTwist", typeof (Int32));
  687. createCol(shapes, "PathTwistBegin", typeof (Int32));
  688. // profile
  689. createCol(shapes, "ProfileBegin", typeof (Int32));
  690. createCol(shapes, "ProfileEnd", typeof (Int32));
  691. createCol(shapes, "ProfileCurve", typeof (Int32));
  692. createCol(shapes, "ProfileHollow", typeof (Int32));
  693. createCol(shapes, "State", typeof(Int32));
  694. createCol(shapes, "Texture", typeof (Byte[]));
  695. createCol(shapes, "ExtraParams", typeof (Byte[]));
  696. shapes.PrimaryKey = new DataColumn[] {shapes.Columns["UUID"]};
  697. return shapes;
  698. }
  699. private static DataTable createItemsTable()
  700. {
  701. DataTable items = new DataTable("primitems");
  702. createCol(items, "itemID", typeof (String));
  703. createCol(items, "primID", typeof (String));
  704. createCol(items, "assetID", typeof (String));
  705. createCol(items, "parentFolderID", typeof (String));
  706. createCol(items, "invType", typeof (Int32));
  707. createCol(items, "assetType", typeof (Int32));
  708. createCol(items, "name", typeof (String));
  709. createCol(items, "description", typeof (String));
  710. createCol(items, "creationDate", typeof (Int64));
  711. createCol(items, "creatorID", typeof (String));
  712. createCol(items, "ownerID", typeof (String));
  713. createCol(items, "lastOwnerID", typeof (String));
  714. createCol(items, "groupID", typeof (String));
  715. createCol(items, "nextPermissions", typeof (Int32));
  716. createCol(items, "currentPermissions", typeof (Int32));
  717. createCol(items, "basePermissions", typeof (Int32));
  718. createCol(items, "everyonePermissions", typeof (Int32));
  719. createCol(items, "groupPermissions", typeof (Int32));
  720. items.PrimaryKey = new DataColumn[] {items.Columns["itemID"]};
  721. return items;
  722. }
  723. /***********************************************************************
  724. *
  725. * Convert between ADO.NET <=> OpenSim Objects
  726. *
  727. * These should be database independant
  728. *
  729. **********************************************************************/
  730. private SceneObjectPart buildPrim(DataRow row)
  731. {
  732. SceneObjectPart prim = new SceneObjectPart();
  733. prim.UUID = new LLUUID((String) row["UUID"]);
  734. // explicit conversion of integers is required, which sort
  735. // of sucks. No idea if there is a shortcut here or not.
  736. prim.ParentID = Convert.ToUInt32(row["ParentID"]);
  737. prim.CreationDate = Convert.ToInt32(row["CreationDate"]);
  738. prim.Name = (String) row["Name"];
  739. // various text fields
  740. prim.Text = (String) row["Text"];
  741. prim.Description = (String) row["Description"];
  742. prim.SitName = (String) row["SitName"];
  743. prim.TouchName = (String) row["TouchName"];
  744. // permissions
  745. prim.ObjectFlags = Convert.ToUInt32(row["ObjectFlags"]);
  746. prim.CreatorID = new LLUUID((String) row["CreatorID"]);
  747. prim.OwnerID = new LLUUID((String) row["OwnerID"]);
  748. prim.GroupID = new LLUUID((String) row["GroupID"]);
  749. prim.LastOwnerID = new LLUUID((String) row["LastOwnerID"]);
  750. prim.OwnerMask = Convert.ToUInt32(row["OwnerMask"]);
  751. prim.NextOwnerMask = Convert.ToUInt32(row["NextOwnerMask"]);
  752. prim.GroupMask = Convert.ToUInt32(row["GroupMask"]);
  753. prim.EveryoneMask = Convert.ToUInt32(row["EveryoneMask"]);
  754. prim.BaseMask = Convert.ToUInt32(row["BaseMask"]);
  755. // vectors
  756. prim.OffsetPosition = new LLVector3(
  757. Convert.ToSingle(row["PositionX"]),
  758. Convert.ToSingle(row["PositionY"]),
  759. Convert.ToSingle(row["PositionZ"])
  760. );
  761. prim.GroupPosition = new LLVector3(
  762. Convert.ToSingle(row["GroupPositionX"]),
  763. Convert.ToSingle(row["GroupPositionY"]),
  764. Convert.ToSingle(row["GroupPositionZ"])
  765. );
  766. prim.Velocity = new LLVector3(
  767. Convert.ToSingle(row["VelocityX"]),
  768. Convert.ToSingle(row["VelocityY"]),
  769. Convert.ToSingle(row["VelocityZ"])
  770. );
  771. prim.AngularVelocity = new LLVector3(
  772. Convert.ToSingle(row["AngularVelocityX"]),
  773. Convert.ToSingle(row["AngularVelocityY"]),
  774. Convert.ToSingle(row["AngularVelocityZ"])
  775. );
  776. prim.Acceleration = new LLVector3(
  777. Convert.ToSingle(row["AccelerationX"]),
  778. Convert.ToSingle(row["AccelerationY"]),
  779. Convert.ToSingle(row["AccelerationZ"])
  780. );
  781. // quaternions
  782. prim.RotationOffset = new LLQuaternion(
  783. Convert.ToSingle(row["RotationX"]),
  784. Convert.ToSingle(row["RotationY"]),
  785. Convert.ToSingle(row["RotationZ"]),
  786. Convert.ToSingle(row["RotationW"])
  787. );
  788. try
  789. {
  790. prim.SetSitTargetLL(new LLVector3(
  791. Convert.ToSingle(row["SitTargetOffsetX"]),
  792. Convert.ToSingle(row["SitTargetOffsetY"]),
  793. Convert.ToSingle(row["SitTargetOffsetZ"])), new LLQuaternion(
  794. Convert.ToSingle(
  795. row["SitTargetOrientX"]),
  796. Convert.ToSingle(
  797. row["SitTargetOrientY"]),
  798. Convert.ToSingle(
  799. row["SitTargetOrientZ"]),
  800. Convert.ToSingle(
  801. row["SitTargetOrientW"])));
  802. }
  803. catch (InvalidCastException)
  804. {
  805. // Database table was created before we got here and needs to be created! :P
  806. using (
  807. MySqlCommand cmd =
  808. new MySqlCommand(
  809. "ALTER TABLE `prims` ADD COLUMN `SitTargetOffsetX` float NOT NULL default 0, ADD COLUMN `SitTargetOffsetY` float NOT NULL default 0, ADD COLUMN `SitTargetOffsetZ` float NOT NULL default 0, ADD COLUMN `SitTargetOrientW` float NOT NULL default 0, ADD COLUMN `SitTargetOrientX` float NOT NULL default 0, ADD COLUMN `SitTargetOrientY` float NOT NULL default 0, ADD COLUMN `SitTargetOrientZ` float NOT NULL default 0;",
  810. m_connection))
  811. {
  812. cmd.ExecuteNonQuery();
  813. }
  814. }
  815. return prim;
  816. }
  817. /// <summary>
  818. /// Build a prim inventory item from the persisted data.
  819. /// </summary>
  820. /// <param name="row"></param>
  821. /// <returns></returns>
  822. private static TaskInventoryItem buildItem(DataRow row)
  823. {
  824. TaskInventoryItem taskItem = new TaskInventoryItem();
  825. taskItem.ItemID = new LLUUID((String)row["itemID"]);
  826. taskItem.ParentPartID = new LLUUID((String)row["primID"]);
  827. taskItem.AssetID = new LLUUID((String)row["assetID"]);
  828. taskItem.ParentID = new LLUUID((String)row["parentFolderID"]);
  829. taskItem.InvType = Convert.ToInt32(row["invType"]);
  830. taskItem.Type = Convert.ToInt32(row["assetType"]);
  831. taskItem.Name = (String)row["name"];
  832. taskItem.Description = (String)row["description"];
  833. taskItem.CreationDate = Convert.ToUInt32(row["creationDate"]);
  834. taskItem.CreatorID = new LLUUID((String)row["creatorID"]);
  835. taskItem.OwnerID = new LLUUID((String)row["ownerID"]);
  836. taskItem.LastOwnerID = new LLUUID((String)row["lastOwnerID"]);
  837. taskItem.GroupID = new LLUUID((String)row["groupID"]);
  838. taskItem.NextOwnerMask = Convert.ToUInt32(row["nextPermissions"]);
  839. taskItem.OwnerMask = Convert.ToUInt32(row["currentPermissions"]);
  840. taskItem.BaseMask = Convert.ToUInt32(row["basePermissions"]);
  841. taskItem.EveryoneMask = Convert.ToUInt32(row["everyonePermissions"]);
  842. taskItem.GroupMask = Convert.ToUInt32(row["groupPermissions"]);
  843. return taskItem;
  844. }
  845. private static LandData buildLandData(DataRow row)
  846. {
  847. LandData newData = new LandData();
  848. newData.globalID = new LLUUID((String) row["UUID"]);
  849. newData.localID = Convert.ToInt32(row["LocalLandID"]);
  850. // Bitmap is a byte[512]
  851. newData.landBitmapByteArray = (Byte[]) row["Bitmap"];
  852. newData.landName = (String) row["Name"];
  853. newData.landDesc = (String) row["Description"];
  854. newData.ownerID = (String) row["OwnerUUID"];
  855. newData.isGroupOwned = Convert.ToBoolean(row["IsGroupOwned"]);
  856. newData.area = Convert.ToInt32(row["Area"]);
  857. newData.auctionID = Convert.ToUInt32(row["AuctionID"]); //Unemplemented
  858. newData.category = (Parcel.ParcelCategory) Convert.ToInt32(row["Category"]);
  859. //Enum libsecondlife.Parcel.ParcelCategory
  860. newData.claimDate = Convert.ToInt32(row["ClaimDate"]);
  861. newData.claimPrice = Convert.ToInt32(row["ClaimPrice"]);
  862. newData.groupID = new LLUUID((String) row["GroupUUID"]);
  863. newData.salePrice = Convert.ToInt32(row["SalePrice"]);
  864. newData.landStatus = (Parcel.ParcelStatus) Convert.ToInt32(row["LandStatus"]);
  865. //Enum. libsecondlife.Parcel.ParcelStatus
  866. newData.landFlags = Convert.ToUInt32(row["LandFlags"]);
  867. newData.landingType = Convert.ToByte(row["LandingType"]);
  868. newData.mediaAutoScale = Convert.ToByte(row["MediaAutoScale"]);
  869. newData.mediaID = new LLUUID((String) row["MediaTextureUUID"]);
  870. newData.mediaURL = (String) row["MediaURL"];
  871. newData.musicURL = (String) row["MusicURL"];
  872. newData.passHours = Convert.ToSingle(row["PassHours"]);
  873. newData.passPrice = Convert.ToInt32(row["PassPrice"]);
  874. LLUUID authedbuyer = LLUUID.Zero;
  875. LLUUID snapshotID = LLUUID.Zero;
  876. Helpers.TryParse((string)row["AuthBuyerID"], out authedbuyer);
  877. Helpers.TryParse((string)row["SnapshotUUID"], out snapshotID);
  878. newData.authBuyerID = authedbuyer;
  879. newData.snapshotID = snapshotID;
  880. newData.userLocation =
  881. new LLVector3(Convert.ToSingle(row["UserLocationX"]), Convert.ToSingle(row["UserLocationY"]),
  882. Convert.ToSingle(row["UserLocationZ"]));
  883. newData.userLookAt =
  884. new LLVector3(Convert.ToSingle(row["UserLookAtX"]), Convert.ToSingle(row["UserLookAtY"]),
  885. Convert.ToSingle(row["UserLookAtZ"]));
  886. newData.parcelAccessList = new List<ParcelManager.ParcelAccessEntry>();
  887. return newData;
  888. }
  889. private static ParcelManager.ParcelAccessEntry buildLandAccessData(DataRow row)
  890. {
  891. ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry();
  892. entry.AgentID = new LLUUID((string) row["AccessUUID"]);
  893. entry.Flags = (ParcelManager.AccessList) Convert.ToInt32(row["Flags"]);
  894. entry.Time = new DateTime();
  895. return entry;
  896. }
  897. private static Array serializeTerrain(double[,] val)
  898. {
  899. MemoryStream str = new MemoryStream(65536*sizeof (double));
  900. BinaryWriter bw = new BinaryWriter(str);
  901. // TODO: COMPATIBILITY - Add byte-order conversions
  902. for (int x = 0; x < 256; x++)
  903. for (int y = 0; y < 256; y++)
  904. bw.Write(val[x, y]);
  905. return str.ToArray();
  906. }
  907. private void fillPrimRow(DataRow row, SceneObjectPart prim, LLUUID sceneGroupID, LLUUID regionUUID)
  908. {
  909. row["UUID"] = Util.ToRawUuidString(prim.UUID);
  910. row["RegionUUID"] = Util.ToRawUuidString(regionUUID);
  911. row["ParentID"] = prim.ParentID;
  912. row["CreationDate"] = prim.CreationDate;
  913. row["Name"] = prim.Name;
  914. row["SceneGroupID"] = Util.ToRawUuidString(sceneGroupID);
  915. // the UUID of the root part for this SceneObjectGroup
  916. // various text fields
  917. row["Text"] = prim.Text;
  918. row["Description"] = prim.Description;
  919. row["SitName"] = prim.SitName;
  920. row["TouchName"] = prim.TouchName;
  921. // permissions
  922. row["ObjectFlags"] = prim.ObjectFlags;
  923. row["CreatorID"] = Util.ToRawUuidString(prim.CreatorID);
  924. row["OwnerID"] = Util.ToRawUuidString(prim.OwnerID);
  925. row["GroupID"] = Util.ToRawUuidString(prim.GroupID);
  926. row["LastOwnerID"] = Util.ToRawUuidString(prim.LastOwnerID);
  927. row["OwnerMask"] = prim.OwnerMask;
  928. row["NextOwnerMask"] = prim.NextOwnerMask;
  929. row["GroupMask"] = prim.GroupMask;
  930. row["EveryoneMask"] = prim.EveryoneMask;
  931. row["BaseMask"] = prim.BaseMask;
  932. // vectors
  933. row["PositionX"] = prim.OffsetPosition.X;
  934. row["PositionY"] = prim.OffsetPosition.Y;
  935. row["PositionZ"] = prim.OffsetPosition.Z;
  936. row["GroupPositionX"] = prim.GroupPosition.X;
  937. row["GroupPositionY"] = prim.GroupPosition.Y;
  938. row["GroupPositionZ"] = prim.GroupPosition.Z;
  939. row["VelocityX"] = prim.Velocity.X;
  940. row["VelocityY"] = prim.Velocity.Y;
  941. row["VelocityZ"] = prim.Velocity.Z;
  942. row["AngularVelocityX"] = prim.AngularVelocity.X;
  943. row["AngularVelocityY"] = prim.AngularVelocity.Y;
  944. row["AngularVelocityZ"] = prim.AngularVelocity.Z;
  945. row["AccelerationX"] = prim.Acceleration.X;
  946. row["AccelerationY"] = prim.Acceleration.Y;
  947. row["AccelerationZ"] = prim.Acceleration.Z;
  948. // quaternions
  949. row["RotationX"] = prim.RotationOffset.X;
  950. row["RotationY"] = prim.RotationOffset.Y;
  951. row["RotationZ"] = prim.RotationOffset.Z;
  952. row["RotationW"] = prim.RotationOffset.W;
  953. try
  954. {
  955. // Sit target
  956. LLVector3 sitTargetPos = prim.GetSitTargetPositionLL();
  957. row["SitTargetOffsetX"] = sitTargetPos.X;
  958. row["SitTargetOffsetY"] = sitTargetPos.Y;
  959. row["SitTargetOffsetZ"] = sitTargetPos.Z;
  960. LLQuaternion sitTargetOrient = prim.GetSitTargetOrientationLL();
  961. row["SitTargetOrientW"] = sitTargetOrient.W;
  962. row["SitTargetOrientX"] = sitTargetOrient.X;
  963. row["SitTargetOrientY"] = sitTargetOrient.Y;
  964. row["SitTargetOrientZ"] = sitTargetOrient.Z;
  965. }
  966. catch (MySqlException)
  967. {
  968. // Database table was created before we got here and needs to be created! :P
  969. using (
  970. MySqlCommand cmd =
  971. new MySqlCommand(
  972. "ALTER TABLE `prims` ADD COLUMN `SitTargetOffsetX` float NOT NULL default 0, ADD COLUMN `SitTargetOffsetY` float NOT NULL default 0, ADD COLUMN `SitTargetOffsetZ` float NOT NULL default 0, ADD COLUMN `SitTargetOrientW` float NOT NULL default 0, ADD COLUMN `SitTargetOrientX` float NOT NULL default 0, ADD COLUMN `SitTargetOrientY` float NOT NULL default 0, ADD COLUMN `SitTargetOrientZ` float NOT NULL default 0;",
  973. m_connection))
  974. {
  975. cmd.ExecuteNonQuery();
  976. }
  977. }
  978. }
  979. private static void fillItemRow(DataRow row, TaskInventoryItem taskItem)
  980. {
  981. row["itemID"] = taskItem.ItemID;
  982. row["primID"] = taskItem.ParentPartID;
  983. row["assetID"] = taskItem.AssetID;
  984. row["parentFolderID"] = taskItem.ParentID;
  985. row["invType"] = taskItem.InvType;
  986. row["assetType"] = taskItem.Type;
  987. row["name"] = taskItem.Name;
  988. row["description"] = taskItem.Description;
  989. row["creationDate"] = taskItem.CreationDate;
  990. row["creatorID"] = taskItem.CreatorID;
  991. row["ownerID"] = taskItem.OwnerID;
  992. row["lastOwnerID"] = taskItem.LastOwnerID;
  993. row["groupID"] = taskItem.GroupID;
  994. row["nextPermissions"] = taskItem.NextOwnerMask;
  995. row["currentPermissions"] = taskItem.OwnerMask;
  996. row["basePermissions"] = taskItem.BaseMask;
  997. row["everyonePermissions"] = taskItem.EveryoneMask;
  998. row["groupPermissions"] = taskItem.GroupMask;
  999. }
  1000. private static void fillLandRow(DataRow row, LandData land, LLUUID regionUUID)
  1001. {
  1002. row["UUID"] = Util.ToRawUuidString(land.globalID);
  1003. row["RegionUUID"] = Util.ToRawUuidString(regionUUID);
  1004. row["LocalLandID"] = land.localID;
  1005. // Bitmap is a byte[512]
  1006. row["Bitmap"] = land.landBitmapByteArray;
  1007. row["Name"] = land.landName;
  1008. row["Description"] = land.landDesc;
  1009. row["OwnerUUID"] = Util.ToRawUuidString(land.ownerID);
  1010. row["IsGroupOwned"] = land.isGroupOwned;
  1011. row["Area"] = land.area;
  1012. row["AuctionID"] = land.auctionID; //Unemplemented
  1013. row["Category"] = land.category; //Enum libsecondlife.Parcel.ParcelCategory
  1014. row["ClaimDate"] = land.claimDate;
  1015. row["ClaimPrice"] = land.claimPrice;
  1016. row["GroupUUID"] = Util.ToRawUuidString(land.groupID);
  1017. row["SalePrice"] = land.salePrice;
  1018. row["LandStatus"] = land.landStatus; //Enum. libsecondlife.Parcel.ParcelStatus
  1019. row["LandFlags"] = land.landFlags;
  1020. row["LandingType"] = land.landingType;
  1021. row["MediaAutoScale"] = land.mediaAutoScale;
  1022. row["MediaTextureUUID"] = Util.ToRawUuidString(land.mediaID);
  1023. row["MediaURL"] = land.mediaURL;
  1024. row["MusicURL"] = land.musicURL;
  1025. row["PassHours"] = land.passHours;
  1026. row["PassPrice"] = land.passPrice;
  1027. row["SnapshotUUID"] = Util.ToRawUuidString(land.snapshotID);
  1028. row["UserLocationX"] = land.userLocation.X;
  1029. row["UserLocationY"] = land.userLocation.Y;
  1030. row["UserLocationZ"] = land.userLocation.Z;
  1031. row["UserLookAtX"] = land.userLookAt.X;
  1032. row["UserLookAtY"] = land.userLookAt.Y;
  1033. row["UserLookAtZ"] = land.userLookAt.Z;
  1034. row["AuthBuyerID"] = land.authBuyerID;
  1035. }
  1036. private static void fillLandAccessRow(DataRow row, ParcelManager.ParcelAccessEntry entry, LLUUID parcelID)
  1037. {
  1038. row["LandUUID"] = Util.ToRawUuidString(parcelID);
  1039. row["AccessUUID"] = Util.ToRawUuidString(entry.AgentID);
  1040. row["Flags"] = entry.Flags;
  1041. }
  1042. private PrimitiveBaseShape buildShape(DataRow row)
  1043. {
  1044. PrimitiveBaseShape s = new PrimitiveBaseShape();
  1045. s.Scale = new LLVector3(
  1046. Convert.ToSingle(row["ScaleX"]),
  1047. Convert.ToSingle(row["ScaleY"]),
  1048. Convert.ToSingle(row["ScaleZ"])
  1049. );
  1050. // paths
  1051. s.PCode = Convert.ToByte(row["PCode"]);
  1052. s.PathBegin = Convert.ToUInt16(row["PathBegin"]);
  1053. s.PathEnd = Convert.ToUInt16(row["PathEnd"]);
  1054. s.PathScaleX = Convert.ToByte(row["PathScaleX"]);
  1055. s.PathScaleY = Convert.ToByte(row["PathScaleY"]);
  1056. s.PathShearX = Convert.ToByte(row["PathShearX"]);
  1057. s.PathShearY = Convert.ToByte(row["PathShearY"]);
  1058. s.PathSkew = Convert.ToSByte(row["PathSkew"]);
  1059. s.PathCurve = Convert.ToByte(row["PathCurve"]);
  1060. s.PathRadiusOffset = Convert.ToSByte(row["PathRadiusOffset"]);
  1061. s.PathRevolutions = Convert.ToByte(row["PathRevolutions"]);
  1062. s.PathTaperX = Convert.ToSByte(row["PathTaperX"]);
  1063. s.PathTaperY = Convert.ToSByte(row["PathTaperY"]);
  1064. s.PathTwist = Convert.ToSByte(row["PathTwist"]);
  1065. s.PathTwistBegin = Convert.ToSByte(row["PathTwistBegin"]);
  1066. // profile
  1067. s.ProfileBegin = Convert.ToUInt16(row["ProfileBegin"]);
  1068. s.ProfileEnd = Convert.ToUInt16(row["ProfileEnd"]);
  1069. s.ProfileCurve = Convert.ToByte(row["ProfileCurve"]);
  1070. s.ProfileHollow = Convert.ToUInt16(row["ProfileHollow"]);
  1071. byte[] textureEntry = (byte[]) row["Texture"];
  1072. s.TextureEntry = textureEntry;
  1073. s.ExtraParams = (byte[]) row["ExtraParams"];
  1074. try
  1075. {
  1076. s.State = Convert.ToByte(row["State"]);
  1077. }
  1078. catch (InvalidCastException)
  1079. {
  1080. // Database table was created before we got here and needs to be created! :P
  1081. using (
  1082. MySqlCommand cmd =
  1083. new MySqlCommand(
  1084. "ALTER TABLE `primshapes` ADD COLUMN `State` int NOT NULL default 0;",
  1085. m_connection))
  1086. {
  1087. cmd.ExecuteNonQuery();
  1088. }
  1089. }
  1090. return s;
  1091. }
  1092. private void fillShapeRow(DataRow row, SceneObjectPart prim)
  1093. {
  1094. PrimitiveBaseShape s = prim.Shape;
  1095. row["UUID"] = Util.ToRawUuidString(prim.UUID);
  1096. // shape is an enum
  1097. row["Shape"] = 0;
  1098. // vectors
  1099. row["ScaleX"] = s.Scale.X;
  1100. row["ScaleY"] = s.Scale.Y;
  1101. row["ScaleZ"] = s.Scale.Z;
  1102. // paths
  1103. row["PCode"] = s.PCode;
  1104. row["PathBegin"] = s.PathBegin;
  1105. row["PathEnd"] = s.PathEnd;
  1106. row["PathScaleX"] = s.PathScaleX;
  1107. row["PathScaleY"] = s.PathScaleY;
  1108. row["PathShearX"] = s.PathShearX;
  1109. row["PathShearY"] = s.PathShearY;
  1110. row["PathSkew"] = s.PathSkew;
  1111. row["PathCurve"] = s.PathCurve;
  1112. row["PathRadiusOffset"] = s.PathRadiusOffset;
  1113. row["PathRevolutions"] = s.PathRevolutions;
  1114. row["PathTaperX"] = s.PathTaperX;
  1115. row["PathTaperY"] = s.PathTaperY;
  1116. row["PathTwist"] = s.PathTwist;
  1117. row["PathTwistBegin"] = s.PathTwistBegin;
  1118. // profile
  1119. row["ProfileBegin"] = s.ProfileBegin;
  1120. row["ProfileEnd"] = s.ProfileEnd;
  1121. row["ProfileCurve"] = s.ProfileCurve;
  1122. row["ProfileHollow"] = s.ProfileHollow;
  1123. row["Texture"] = s.TextureEntry;
  1124. row["ExtraParams"] = s.ExtraParams;
  1125. try
  1126. {
  1127. row["State"] = s.State;
  1128. }
  1129. catch (MySqlException)
  1130. {
  1131. // Database table was created before we got here and needs to be created! :P
  1132. using (
  1133. MySqlCommand cmd =
  1134. new MySqlCommand(
  1135. "ALTER TABLE `primshapes` ADD COLUMN `State` int NOT NULL default 0;",
  1136. m_connection))
  1137. {
  1138. cmd.ExecuteNonQuery();
  1139. }
  1140. }
  1141. }
  1142. private void addPrim(SceneObjectPart prim, LLUUID sceneGroupID, LLUUID regionUUID)
  1143. {
  1144. DataTable prims = m_dataSet.Tables["prims"];
  1145. DataTable shapes = m_dataSet.Tables["primshapes"];
  1146. DataRow primRow = prims.Rows.Find(Util.ToRawUuidString(prim.UUID));
  1147. if (primRow == null)
  1148. {
  1149. primRow = prims.NewRow();
  1150. fillPrimRow(primRow, prim, sceneGroupID, regionUUID);
  1151. prims.Rows.Add(primRow);
  1152. }
  1153. else
  1154. {
  1155. fillPrimRow(primRow, prim, sceneGroupID, regionUUID);
  1156. }
  1157. DataRow shapeRow = shapes.Rows.Find(Util.ToRawUuidString(prim.UUID));
  1158. if (shapeRow == null)
  1159. {
  1160. shapeRow = shapes.NewRow();
  1161. fillShapeRow(shapeRow, prim);
  1162. shapes.Rows.Add(shapeRow);
  1163. }
  1164. else
  1165. {
  1166. fillShapeRow(shapeRow, prim);
  1167. }
  1168. }
  1169. // see IRegionDatastore
  1170. public void StorePrimInventory(LLUUID primID, ICollection<TaskInventoryItem> items)
  1171. {
  1172. if (!persistPrimInventories)
  1173. return;
  1174. m_log.InfoFormat("[REGION DB]: Persisting Prim Inventory with prim ID {0}", primID);
  1175. // For now, we're just going to crudely remove all the previous inventory items
  1176. // no matter whether they have changed or not, and replace them with the current set.
  1177. lock (m_dataSet)
  1178. {
  1179. RemoveItems(primID);
  1180. // repalce with current inventory details
  1181. foreach (TaskInventoryItem newItem in items)
  1182. {
  1183. // m_log.InfoFormat(
  1184. // "[REGION DB]: " +
  1185. // "Adding item {0}, {1} to prim ID {2}",
  1186. // newItem.Name, newItem.ItemID, newItem.ParentPartID);
  1187. DataRow newItemRow = m_itemsTable.NewRow();
  1188. fillItemRow(newItemRow, newItem);
  1189. m_itemsTable.Rows.Add(newItemRow);
  1190. }
  1191. }
  1192. Commit();
  1193. }
  1194. /***********************************************************************
  1195. *
  1196. * SQL Statement Creation Functions
  1197. *
  1198. * These functions create SQL statements for update, insert, and create.
  1199. * They can probably be factored later to have a db independant
  1200. * portion and a db specific portion
  1201. *
  1202. **********************************************************************/
  1203. private static MySqlCommand createInsertCommand(string table, DataTable dt)
  1204. {
  1205. /**
  1206. * This is subtle enough to deserve some commentary.
  1207. * Instead of doing *lots* and *lots of hardcoded strings
  1208. * for database definitions we'll use the fact that
  1209. * realistically all insert statements look like "insert
  1210. * into A(b, c) values(:b, :c) on the parameterized query
  1211. * front. If we just have a list of b, c, etc... we can
  1212. * generate these strings instead of typing them out.
  1213. */
  1214. string[] cols = new string[dt.Columns.Count];
  1215. for (int i = 0; i < dt.Columns.Count; i++)
  1216. {
  1217. DataColumn col = dt.Columns[i];
  1218. cols[i] = col.ColumnName;
  1219. }
  1220. string sql = "insert into " + table + "(";
  1221. sql += String.Join(", ", cols);
  1222. // important, the first ':' needs to be here, the rest get added in the join
  1223. sql += ") values (?";
  1224. sql += String.Join(", ?", cols);
  1225. sql += ")";
  1226. MySqlCommand cmd = new MySqlCommand(sql);
  1227. // this provides the binding for all our parameters, so
  1228. // much less code than it used to be
  1229. foreach (DataColumn col in dt.Columns)
  1230. {
  1231. cmd.Parameters.Add(createMySqlParameter(col.ColumnName, col.DataType));
  1232. }
  1233. return cmd;
  1234. }
  1235. private static MySqlCommand createUpdateCommand(string table, string pk, DataTable dt)
  1236. {
  1237. string sql = "update " + table + " set ";
  1238. string subsql = String.Empty;
  1239. foreach (DataColumn col in dt.Columns)
  1240. {
  1241. if (subsql.Length > 0)
  1242. {
  1243. // a map function would rock so much here
  1244. subsql += ", ";
  1245. }
  1246. subsql += col.ColumnName + "=?" + col.ColumnName;
  1247. }
  1248. sql += subsql;
  1249. sql += " where " + pk;
  1250. MySqlCommand cmd = new MySqlCommand(sql);
  1251. // this provides the binding for all our parameters, so
  1252. // much less code than it used to be
  1253. foreach (DataColumn col in dt.Columns)
  1254. {
  1255. cmd.Parameters.Add(createMySqlParameter(col.ColumnName, col.DataType));
  1256. }
  1257. return cmd;
  1258. }
  1259. private static string defineTable(DataTable dt)
  1260. {
  1261. string sql = "create table " + dt.TableName + "(";
  1262. string subsql = String.Empty;
  1263. foreach (DataColumn col in dt.Columns)
  1264. {
  1265. if (subsql.Length > 0)
  1266. {
  1267. // a map function would rock so much here
  1268. subsql += ",\n";
  1269. }
  1270. subsql += col.ColumnName + " " + MySqlType(col.DataType);
  1271. if (dt.PrimaryKey.Length > 0 && col == dt.PrimaryKey[0])
  1272. {
  1273. subsql += " primary key";
  1274. }
  1275. }
  1276. sql += subsql;
  1277. sql += ")";
  1278. //m_log.InfoFormat("[DATASTORE]: defineTable() sql {0}", sql);
  1279. return sql;
  1280. }
  1281. /***********************************************************************
  1282. *
  1283. * Database Binding functions
  1284. *
  1285. * These will be db specific due to typing, and minor differences
  1286. * in databases.
  1287. *
  1288. **********************************************************************/
  1289. ///<summary>
  1290. /// This is a convenience function that collapses 5 repetitive
  1291. /// lines for defining MySqlParameters to 2 parameters:
  1292. /// column name and database type.
  1293. ///
  1294. /// It assumes certain conventions like ?param as the param
  1295. /// name to replace in parametrized queries, and that source
  1296. /// version is always current version, both of which are fine
  1297. /// for us.
  1298. ///</summary>
  1299. ///<returns>a built MySql parameter</returns>
  1300. private static MySqlParameter createMySqlParameter(string name, Type type)
  1301. {
  1302. MySqlParameter param = new MySqlParameter();
  1303. param.ParameterName = "?" + name;
  1304. param.DbType = dbtypeFromType(type);
  1305. param.SourceColumn = name;
  1306. param.SourceVersion = DataRowVersion.Current;
  1307. return param;
  1308. }
  1309. private void SetupPrimCommands(MySqlDataAdapter da, MySqlConnection conn)
  1310. {
  1311. MySqlCommand insertCommand = createInsertCommand("prims", m_primTable);
  1312. insertCommand.Connection = conn;
  1313. da.InsertCommand = insertCommand;
  1314. MySqlCommand updateCommand = createUpdateCommand("prims", "UUID=?UUID", m_primTable);
  1315. updateCommand.Connection = conn;
  1316. da.UpdateCommand = updateCommand;
  1317. MySqlCommand delete = new MySqlCommand("delete from prims where UUID=?UUID");
  1318. delete.Parameters.Add(createMySqlParameter("UUID", typeof (String)));
  1319. delete.Connection = conn;
  1320. da.DeleteCommand = delete;
  1321. }
  1322. private void SetupItemsCommands(MySqlDataAdapter da, MySqlConnection conn)
  1323. {
  1324. da.InsertCommand = createInsertCommand("primitems", m_itemsTable);
  1325. da.InsertCommand.Connection = conn;
  1326. da.UpdateCommand = createUpdateCommand("primitems", "itemID = ?itemID", m_itemsTable);
  1327. da.UpdateCommand.Connection = conn;
  1328. MySqlCommand delete = new MySqlCommand("delete from primitems where itemID = ?itemID");
  1329. delete.Parameters.Add(createMySqlParameter("itemID", typeof (String)));
  1330. delete.Connection = conn;
  1331. da.DeleteCommand = delete;
  1332. }
  1333. private void SetupTerrainCommands(MySqlDataAdapter da, MySqlConnection conn)
  1334. {
  1335. da.InsertCommand = createInsertCommand("terrain", m_dataSet.Tables["terrain"]);
  1336. da.InsertCommand.Connection = conn;
  1337. }
  1338. private void setupLandCommands(MySqlDataAdapter da, MySqlConnection conn)
  1339. {
  1340. da.InsertCommand = createInsertCommand("land", m_dataSet.Tables["land"]);
  1341. da.InsertCommand.Connection = conn;
  1342. da.UpdateCommand = createUpdateCommand("land", "UUID=?UUID", m_dataSet.Tables["land"]);
  1343. da.UpdateCommand.Connection = conn;
  1344. }
  1345. private void setupLandAccessCommands(MySqlDataAdapter da, MySqlConnection conn)
  1346. {
  1347. da.InsertCommand = createInsertCommand("landaccesslist", m_dataSet.Tables["landaccesslist"]);
  1348. da.InsertCommand.Connection = conn;
  1349. }
  1350. private void SetupShapeCommands(MySqlDataAdapter da, MySqlConnection conn)
  1351. {
  1352. da.InsertCommand = createInsertCommand("primshapes", m_dataSet.Tables["primshapes"]);
  1353. da.InsertCommand.Connection = conn;
  1354. da.UpdateCommand = createUpdateCommand("primshapes", "UUID=?UUID", m_dataSet.Tables["primshapes"]);
  1355. da.UpdateCommand.Connection = conn;
  1356. MySqlCommand delete = new MySqlCommand("delete from primshapes where UUID = ?UUID");
  1357. delete.Parameters.Add(createMySqlParameter("UUID", typeof (String)));
  1358. delete.Connection = conn;
  1359. da.DeleteCommand = delete;
  1360. }
  1361. private static void InitDB(MySqlConnection conn)
  1362. {
  1363. string createPrims = defineTable(createPrimTable());
  1364. string createShapes = defineTable(createShapeTable());
  1365. string createItems = defineTable(createItemsTable());
  1366. string createTerrain = defineTable(createTerrainTable());
  1367. // Land table is created from the Versionable Test Table routine now.
  1368. //string createLand = defineTable(createLandTable());
  1369. string createLandAccessList = defineTable(createLandAccessListTable());
  1370. MySqlCommand pcmd = new MySqlCommand(createPrims, conn);
  1371. MySqlCommand scmd = new MySqlCommand(createShapes, conn);
  1372. MySqlCommand icmd = new MySqlCommand(createItems, conn);
  1373. MySqlCommand tcmd = new MySqlCommand(createTerrain, conn);
  1374. //MySqlCommand lcmd = new MySqlCommand(createLand, conn);
  1375. MySqlCommand lalcmd = new MySqlCommand(createLandAccessList, conn);
  1376. if (conn.State != ConnectionState.Open)
  1377. {
  1378. try
  1379. {
  1380. conn.Open();
  1381. }
  1382. catch (Exception ex)
  1383. {
  1384. m_log.Error("[REGION DB]: Error connecting to MySQL server: " + ex.Message);
  1385. m_log.Error("[REGION DB]: Application is terminating!");
  1386. Thread.CurrentThread.Abort();
  1387. }
  1388. }
  1389. try
  1390. {
  1391. pcmd.ExecuteNonQuery();
  1392. }
  1393. catch (MySqlException e)
  1394. {
  1395. m_log.WarnFormat("[REGION DB]: Primitives Table Already Exists: {0}", e);
  1396. }
  1397. try
  1398. {
  1399. scmd.ExecuteNonQuery();
  1400. }
  1401. catch (MySqlException e)
  1402. {
  1403. m_log.WarnFormat("[REGION DB]: Shapes Table Already Exists: {0}", e);
  1404. }
  1405. try
  1406. {
  1407. icmd.ExecuteNonQuery();
  1408. }
  1409. catch (MySqlException e)
  1410. {
  1411. m_log.WarnFormat("[REGION DB]: Items Table Already Exists: {0}", e);
  1412. }
  1413. try
  1414. {
  1415. tcmd.ExecuteNonQuery();
  1416. }
  1417. catch (MySqlException e)
  1418. {
  1419. m_log.WarnFormat("[REGION DB]: Terrain Table Already Exists: {0}", e);
  1420. }
  1421. //try
  1422. //{
  1423. //lcmd.ExecuteNonQuery();
  1424. //}
  1425. //catch (MySqlException e)
  1426. //{
  1427. //m_log.WarnFormat("[MySql]: Land Table Already Exists: {0}", e);
  1428. //}
  1429. try
  1430. {
  1431. lalcmd.ExecuteNonQuery();
  1432. }
  1433. catch (MySqlException e)
  1434. {
  1435. m_log.WarnFormat("[REGION DB]: LandAccessList Table Already Exists: {0}", e);
  1436. }
  1437. conn.Close();
  1438. }
  1439. private bool TestTables(MySqlConnection conn)
  1440. {
  1441. MySqlCommand primSelectCmd = new MySqlCommand(m_primSelect, conn);
  1442. MySqlDataAdapter pDa = new MySqlDataAdapter(primSelectCmd);
  1443. MySqlCommand shapeSelectCmd = new MySqlCommand(m_shapeSelect, conn);
  1444. MySqlDataAdapter sDa = new MySqlDataAdapter(shapeSelectCmd);
  1445. MySqlCommand itemsSelectCmd = new MySqlCommand(m_itemsSelect, conn);
  1446. MySqlDataAdapter iDa = new MySqlDataAdapter(itemsSelectCmd);
  1447. MySqlCommand terrainSelectCmd = new MySqlCommand(m_terrainSelect, conn);
  1448. MySqlDataAdapter tDa = new MySqlDataAdapter(terrainSelectCmd);
  1449. MySqlCommand landSelectCmd = new MySqlCommand(m_landSelect, conn);
  1450. MySqlDataAdapter lDa = new MySqlDataAdapter(landSelectCmd);
  1451. MySqlCommand landAccessListSelectCmd = new MySqlCommand(m_landAccessListSelect, conn);
  1452. MySqlDataAdapter lalDa = new MySqlDataAdapter(landAccessListSelectCmd);
  1453. DataSet tmpDS = new DataSet();
  1454. try
  1455. {
  1456. pDa.Fill(tmpDS, "prims");
  1457. sDa.Fill(tmpDS, "primshapes");
  1458. if (persistPrimInventories)
  1459. iDa.Fill(tmpDS, "primitems");
  1460. tDa.Fill(tmpDS, "terrain");
  1461. lDa.Fill(tmpDS, "land");
  1462. lalDa.Fill(tmpDS, "landaccesslist");
  1463. }
  1464. catch (MySqlException)
  1465. {
  1466. m_log.Info("[DATASTORE]: MySql Database doesn't exist... creating");
  1467. InitDB(conn);
  1468. }
  1469. pDa.Fill(tmpDS, "prims");
  1470. sDa.Fill(tmpDS, "primshapes");
  1471. if (persistPrimInventories)
  1472. iDa.Fill(tmpDS, "primitems");
  1473. tDa.Fill(tmpDS, "terrain");
  1474. lDa.Fill(tmpDS, "land");
  1475. lalDa.Fill(tmpDS, "landaccesslist");
  1476. foreach (DataColumn col in createPrimTable().Columns)
  1477. {
  1478. if (!tmpDS.Tables["prims"].Columns.Contains(col.ColumnName))
  1479. {
  1480. m_log.Info("[REGION DB]: Missing required column:" + col.ColumnName);
  1481. return false;
  1482. }
  1483. }
  1484. foreach (DataColumn col in createShapeTable().Columns)
  1485. {
  1486. if (!tmpDS.Tables["primshapes"].Columns.Contains(col.ColumnName))
  1487. {
  1488. m_log.Info("[REGION DB]: Missing required column:" + col.ColumnName);
  1489. return false;
  1490. }
  1491. }
  1492. // XXX primitems should probably go here eventually
  1493. foreach (DataColumn col in createTerrainTable().Columns)
  1494. {
  1495. if (!tmpDS.Tables["terrain"].Columns.Contains(col.ColumnName))
  1496. {
  1497. m_log.Info("[REGION DB]: Missing require column:" + col.ColumnName);
  1498. return false;
  1499. }
  1500. }
  1501. foreach (DataColumn col in createLandTable().Columns)
  1502. {
  1503. if (!tmpDS.Tables["land"].Columns.Contains(col.ColumnName))
  1504. {
  1505. m_log.Info("[REGION DB]: Missing require column:" + col.ColumnName);
  1506. return false;
  1507. }
  1508. }
  1509. foreach (DataColumn col in createLandAccessListTable().Columns)
  1510. {
  1511. if (!tmpDS.Tables["landaccesslist"].Columns.Contains(col.ColumnName))
  1512. {
  1513. m_log.Info("[DATASTORE]: Missing require column:" + col.ColumnName);
  1514. return false;
  1515. }
  1516. }
  1517. return true;
  1518. }
  1519. /***********************************************************************
  1520. *
  1521. * Type conversion functions
  1522. *
  1523. **********************************************************************/
  1524. private static DbType dbtypeFromType(Type type)
  1525. {
  1526. if (type == typeof (String))
  1527. {
  1528. return DbType.String;
  1529. }
  1530. else if (type == typeof (Int32))
  1531. {
  1532. return DbType.Int32;
  1533. }
  1534. else if (type == typeof (Double))
  1535. {
  1536. return DbType.Double;
  1537. }
  1538. else if (type == typeof (Byte))
  1539. {
  1540. return DbType.Byte;
  1541. }
  1542. else if (type == typeof (Double))
  1543. {
  1544. return DbType.Double;
  1545. }
  1546. else if (type == typeof (Byte[]))
  1547. {
  1548. return DbType.Binary;
  1549. }
  1550. else
  1551. {
  1552. return DbType.String;
  1553. }
  1554. }
  1555. // this is something we'll need to implement for each db
  1556. // slightly differently.
  1557. private static string MySqlType(Type type)
  1558. {
  1559. if (type == typeof (String))
  1560. {
  1561. return "varchar(255)";
  1562. }
  1563. else if (type == typeof (Int32))
  1564. {
  1565. return "integer";
  1566. }
  1567. else if (type == typeof (Int64))
  1568. {
  1569. return "bigint";
  1570. }
  1571. else if (type == typeof (Double))
  1572. {
  1573. return "float";
  1574. }
  1575. else if (type == typeof (Byte[]))
  1576. {
  1577. return "longblob";
  1578. }
  1579. else
  1580. {
  1581. return "string";
  1582. }
  1583. }
  1584. }
  1585. }