1
0

MySQLDataStore.cs 75 KB

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