SQLiteRegionData.cs 74 KB

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