MSSQLDataStore.cs 67 KB

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