MSSQLDataStore.cs 67 KB

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