MSSQLDataStore.cs 67 KB

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