SQLiteSimulationData.cs 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363
  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 OpenSimulator 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.Drawing;
  31. using System.IO;
  32. using System.Reflection;
  33. using log4net;
  34. #if CSharpSqlite
  35. using Community.CsharpSqlite.Sqlite;
  36. #else
  37. using Mono.Data.Sqlite;
  38. #endif
  39. using OpenMetaverse;
  40. using OpenMetaverse.StructuredData;
  41. using OpenSim.Framework;
  42. using OpenSim.Region.Framework.Interfaces;
  43. using OpenSim.Region.Framework.Scenes;
  44. namespace OpenSim.Data.SQLite
  45. {
  46. /// <summary>
  47. /// A RegionData Interface to the SQLite database
  48. /// </summary>
  49. public class SQLiteSimulationData : ISimulationDataStore
  50. {
  51. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  52. private const string primSelect = "select * from prims";
  53. private const string shapeSelect = "select * from primshapes";
  54. private const string itemsSelect = "select * from primitems";
  55. private const string terrainSelect = "select * from terrain limit 1";
  56. private const string landSelect = "select * from land";
  57. private const string landAccessListSelect = "select distinct * from landaccesslist";
  58. private const string regionbanListSelect = "select * from regionban";
  59. private const string regionSettingsSelect = "select * from regionsettings";
  60. private DataSet ds;
  61. private SqliteDataAdapter primDa;
  62. private SqliteDataAdapter shapeDa;
  63. private SqliteDataAdapter itemsDa;
  64. private SqliteDataAdapter terrainDa;
  65. private SqliteDataAdapter landDa;
  66. private SqliteDataAdapter landAccessListDa;
  67. private SqliteDataAdapter regionSettingsDa;
  68. private SqliteConnection m_conn;
  69. private String m_connectionString;
  70. public SQLiteSimulationData()
  71. {
  72. }
  73. public SQLiteSimulationData(string connectionString)
  74. {
  75. Initialise(connectionString);
  76. }
  77. // Temporary attribute while this is experimental
  78. /***********************************************************************
  79. *
  80. * Public Interface Functions
  81. *
  82. **********************************************************************/
  83. /// <summary>
  84. /// <list type="bullet">
  85. /// <item>Initialises RegionData Interface</item>
  86. /// <item>Loads and initialises a new SQLite connection and maintains it.</item>
  87. /// </list>
  88. /// </summary>
  89. /// <param name="connectionString">the connection string</param>
  90. public void Initialise(string connectionString)
  91. {
  92. try
  93. {
  94. m_connectionString = connectionString;
  95. ds = new DataSet("Region");
  96. m_log.Info("[SQLITE REGION DB]: Sqlite - connecting: " + connectionString);
  97. m_conn = new SqliteConnection(m_connectionString);
  98. m_conn.Open();
  99. SqliteCommand primSelectCmd = new SqliteCommand(primSelect, m_conn);
  100. primDa = new SqliteDataAdapter(primSelectCmd);
  101. SqliteCommand shapeSelectCmd = new SqliteCommand(shapeSelect, m_conn);
  102. shapeDa = new SqliteDataAdapter(shapeSelectCmd);
  103. // SqliteCommandBuilder shapeCb = new SqliteCommandBuilder(shapeDa);
  104. SqliteCommand itemsSelectCmd = new SqliteCommand(itemsSelect, m_conn);
  105. itemsDa = new SqliteDataAdapter(itemsSelectCmd);
  106. SqliteCommand terrainSelectCmd = new SqliteCommand(terrainSelect, m_conn);
  107. terrainDa = new SqliteDataAdapter(terrainSelectCmd);
  108. SqliteCommand landSelectCmd = new SqliteCommand(landSelect, m_conn);
  109. landDa = new SqliteDataAdapter(landSelectCmd);
  110. SqliteCommand landAccessListSelectCmd = new SqliteCommand(landAccessListSelect, m_conn);
  111. landAccessListDa = new SqliteDataAdapter(landAccessListSelectCmd);
  112. SqliteCommand regionSettingsSelectCmd = new SqliteCommand(regionSettingsSelect, m_conn);
  113. regionSettingsDa = new SqliteDataAdapter(regionSettingsSelectCmd);
  114. // This actually does the roll forward assembly stuff
  115. Assembly assem = GetType().Assembly;
  116. Migration m = new Migration(m_conn, assem, "RegionStore");
  117. m.Update();
  118. lock (ds)
  119. {
  120. ds.Tables.Add(createPrimTable());
  121. setupPrimCommands(primDa, m_conn);
  122. ds.Tables.Add(createShapeTable());
  123. setupShapeCommands(shapeDa, m_conn);
  124. ds.Tables.Add(createItemsTable());
  125. setupItemsCommands(itemsDa, m_conn);
  126. ds.Tables.Add(createTerrainTable());
  127. setupTerrainCommands(terrainDa, m_conn);
  128. ds.Tables.Add(createLandTable());
  129. setupLandCommands(landDa, m_conn);
  130. ds.Tables.Add(createLandAccessListTable());
  131. setupLandAccessCommands(landAccessListDa, m_conn);
  132. ds.Tables.Add(createRegionSettingsTable());
  133. setupRegionSettingsCommands(regionSettingsDa, m_conn);
  134. // WORKAROUND: This is a work around for sqlite on
  135. // windows, which gets really unhappy with blob columns
  136. // that have no sample data in them. At some point we
  137. // need to actually find a proper way to handle this.
  138. try
  139. {
  140. primDa.Fill(ds.Tables["prims"]);
  141. }
  142. catch (Exception)
  143. {
  144. m_log.Info("[SQLITE REGION DB]: Caught fill error on prims table");
  145. }
  146. try
  147. {
  148. shapeDa.Fill(ds.Tables["primshapes"]);
  149. }
  150. catch (Exception)
  151. {
  152. m_log.Info("[SQLITE REGION DB]: Caught fill error on primshapes table");
  153. }
  154. try
  155. {
  156. itemsDa.Fill(ds.Tables["primitems"]);
  157. }
  158. catch (Exception)
  159. {
  160. m_log.Info("[SQLITE REGION DB]: Caught fill error on primitems table");
  161. }
  162. try
  163. {
  164. terrainDa.Fill(ds.Tables["terrain"]);
  165. }
  166. catch (Exception)
  167. {
  168. m_log.Info("[SQLITE REGION DB]: Caught fill error on terrain table");
  169. }
  170. try
  171. {
  172. landDa.Fill(ds.Tables["land"]);
  173. }
  174. catch (Exception)
  175. {
  176. m_log.Info("[SQLITE REGION DB]: Caught fill error on land table");
  177. }
  178. try
  179. {
  180. landAccessListDa.Fill(ds.Tables["landaccesslist"]);
  181. }
  182. catch (Exception)
  183. {
  184. m_log.Info("[SQLITE REGION DB]: Caught fill error on landaccesslist table");
  185. }
  186. try
  187. {
  188. regionSettingsDa.Fill(ds.Tables["regionsettings"]);
  189. }
  190. catch (Exception)
  191. {
  192. m_log.Info("[SQLITE REGION DB]: Caught fill error on regionsettings table");
  193. }
  194. // We have to create a data set mapping for every table, otherwise the IDataAdaptor.Update() will not populate rows with values!
  195. // Not sure exactly why this is - this kind of thing was not necessary before - justincc 20100409
  196. // Possibly because we manually set up our own DataTables before connecting to the database
  197. CreateDataSetMapping(primDa, "prims");
  198. CreateDataSetMapping(shapeDa, "primshapes");
  199. CreateDataSetMapping(itemsDa, "primitems");
  200. CreateDataSetMapping(terrainDa, "terrain");
  201. CreateDataSetMapping(landDa, "land");
  202. CreateDataSetMapping(landAccessListDa, "landaccesslist");
  203. CreateDataSetMapping(regionSettingsDa, "regionsettings");
  204. }
  205. }
  206. catch (Exception e)
  207. {
  208. m_log.Error(e);
  209. Environment.Exit(23);
  210. }
  211. return;
  212. }
  213. public void Dispose()
  214. {
  215. if (m_conn != null)
  216. {
  217. m_conn.Close();
  218. m_conn = null;
  219. }
  220. if (ds != null)
  221. {
  222. ds.Dispose();
  223. ds = null;
  224. }
  225. if (primDa != null)
  226. {
  227. primDa.Dispose();
  228. primDa = null;
  229. }
  230. if (shapeDa != null)
  231. {
  232. shapeDa.Dispose();
  233. shapeDa = null;
  234. }
  235. if (itemsDa != null)
  236. {
  237. itemsDa.Dispose();
  238. itemsDa = null;
  239. }
  240. if (terrainDa != null)
  241. {
  242. terrainDa.Dispose();
  243. terrainDa = null;
  244. }
  245. if (landDa != null)
  246. {
  247. landDa.Dispose();
  248. landDa = null;
  249. }
  250. if (landAccessListDa != null)
  251. {
  252. landAccessListDa.Dispose();
  253. landAccessListDa = null;
  254. }
  255. if (regionSettingsDa != null)
  256. {
  257. regionSettingsDa.Dispose();
  258. regionSettingsDa = null;
  259. }
  260. }
  261. public void StoreRegionSettings(RegionSettings rs)
  262. {
  263. lock (ds)
  264. {
  265. DataTable regionsettings = ds.Tables["regionsettings"];
  266. DataRow settingsRow = regionsettings.Rows.Find(rs.RegionUUID.ToString());
  267. if (settingsRow == null)
  268. {
  269. settingsRow = regionsettings.NewRow();
  270. fillRegionSettingsRow(settingsRow, rs);
  271. regionsettings.Rows.Add(settingsRow);
  272. }
  273. else
  274. {
  275. fillRegionSettingsRow(settingsRow, rs);
  276. }
  277. Commit();
  278. }
  279. }
  280. public RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID)
  281. {
  282. //This connector doesn't support the windlight module yet
  283. //Return default LL windlight settings
  284. return new RegionLightShareData();
  285. }
  286. public void RemoveRegionWindlightSettings(UUID regionID)
  287. {
  288. }
  289. public void StoreRegionWindlightSettings(RegionLightShareData wl)
  290. {
  291. //This connector doesn't support the windlight module yet
  292. }
  293. public RegionSettings LoadRegionSettings(UUID regionUUID)
  294. {
  295. lock (ds)
  296. {
  297. DataTable regionsettings = ds.Tables["regionsettings"];
  298. string searchExp = "regionUUID = '" + regionUUID.ToString() + "'";
  299. DataRow[] rawsettings = regionsettings.Select(searchExp);
  300. if (rawsettings.Length == 0)
  301. {
  302. RegionSettings rs = new RegionSettings();
  303. rs.RegionUUID = regionUUID;
  304. rs.OnSave += StoreRegionSettings;
  305. StoreRegionSettings(rs);
  306. return rs;
  307. }
  308. DataRow row = rawsettings[0];
  309. RegionSettings newSettings = buildRegionSettings(row);
  310. newSettings.OnSave += StoreRegionSettings;
  311. return newSettings;
  312. }
  313. }
  314. /// <summary>
  315. /// Adds an object into region storage
  316. /// </summary>
  317. /// <param name="obj">the object</param>
  318. /// <param name="regionUUID">the region UUID</param>
  319. public void StoreObject(SceneObjectGroup obj, UUID regionUUID)
  320. {
  321. uint flags = obj.RootPart.GetEffectiveObjectFlags();
  322. // Eligibility check
  323. //
  324. if ((flags & (uint)PrimFlags.Temporary) != 0)
  325. return;
  326. if ((flags & (uint)PrimFlags.TemporaryOnRez) != 0)
  327. return;
  328. lock (ds)
  329. {
  330. foreach (SceneObjectPart prim in obj.Parts)
  331. {
  332. // m_log.Info("[REGION DB]: Adding obj: " + obj.UUID + " to region: " + regionUUID);
  333. addPrim(prim, obj.UUID, regionUUID);
  334. }
  335. }
  336. Commit();
  337. // m_log.Info("[Dump of prims]: " + ds.GetXml());
  338. }
  339. /// <summary>
  340. /// Removes an object from region storage
  341. /// </summary>
  342. /// <param name="obj">the object</param>
  343. /// <param name="regionUUID">the region UUID</param>
  344. public void RemoveObject(UUID obj, UUID regionUUID)
  345. {
  346. // m_log.InfoFormat("[REGION DB]: Removing obj: {0} from region: {1}", obj.Guid, regionUUID);
  347. DataTable prims = ds.Tables["prims"];
  348. DataTable shapes = ds.Tables["primshapes"];
  349. string selectExp = "SceneGroupID = '" + obj + "' and RegionUUID = '" + regionUUID + "'";
  350. lock (ds)
  351. {
  352. DataRow[] primRows = prims.Select(selectExp);
  353. foreach (DataRow row in primRows)
  354. {
  355. // Remove shape rows
  356. UUID uuid = new UUID((string) row["UUID"]);
  357. DataRow shapeRow = shapes.Rows.Find(uuid.ToString());
  358. if (shapeRow != null)
  359. {
  360. shapeRow.Delete();
  361. }
  362. RemoveItems(uuid);
  363. // Remove prim row
  364. row.Delete();
  365. }
  366. }
  367. Commit();
  368. }
  369. /// <summary>
  370. /// Remove all persisted items of the given prim.
  371. /// The caller must acquire the necessrary synchronization locks and commit or rollback changes.
  372. /// </summary>
  373. /// <param name="uuid">The item UUID</param>
  374. private void RemoveItems(UUID uuid)
  375. {
  376. DataTable items = ds.Tables["primitems"];
  377. String sql = String.Format("primID = '{0}'", uuid);
  378. DataRow[] itemRows = items.Select(sql);
  379. foreach (DataRow itemRow in itemRows)
  380. {
  381. itemRow.Delete();
  382. }
  383. }
  384. /// <summary>
  385. /// Load persisted objects from region storage.
  386. /// </summary>
  387. /// <param name="regionUUID">The region UUID</param>
  388. /// <returns>List of loaded groups</returns>
  389. public List<SceneObjectGroup> LoadObjects(UUID regionUUID)
  390. {
  391. Dictionary<UUID, SceneObjectGroup> createdObjects = new Dictionary<UUID, SceneObjectGroup>();
  392. List<SceneObjectGroup> retvals = new List<SceneObjectGroup>();
  393. DataTable prims = ds.Tables["prims"];
  394. DataTable shapes = ds.Tables["primshapes"];
  395. string byRegion = "RegionUUID = '" + regionUUID + "'";
  396. lock (ds)
  397. {
  398. DataRow[] primsForRegion = prims.Select(byRegion);
  399. // m_log.Info("[SQLITE REGION DB]: Loaded " + primsForRegion.Length + " prims for region: " + regionUUID);
  400. // First, create all groups
  401. foreach (DataRow primRow in primsForRegion)
  402. {
  403. try
  404. {
  405. SceneObjectPart prim = null;
  406. string uuid = (string) primRow["UUID"];
  407. string objID = (string) primRow["SceneGroupID"];
  408. if (uuid == objID) //is new SceneObjectGroup ?
  409. {
  410. prim = buildPrim(primRow);
  411. DataRow shapeRow = shapes.Rows.Find(prim.UUID.ToString());
  412. if (shapeRow != null)
  413. {
  414. prim.Shape = buildShape(shapeRow);
  415. }
  416. else
  417. {
  418. m_log.Warn(
  419. "[SQLITE REGION DB]: No shape found for prim in storage, so setting default box shape");
  420. prim.Shape = PrimitiveBaseShape.Default;
  421. }
  422. SceneObjectGroup group = new SceneObjectGroup(prim);
  423. createdObjects.Add(group.UUID, group);
  424. retvals.Add(group);
  425. LoadItems(prim);
  426. }
  427. }
  428. catch (Exception e)
  429. {
  430. m_log.Error("[SQLITE REGION DB]: Failed create prim object in new group, exception and data follows");
  431. m_log.Error("[SQLITE REGION DB]: ", e);
  432. foreach (DataColumn col in prims.Columns)
  433. {
  434. m_log.Error("[SQLITE REGION DB]: Col: " + col.ColumnName + " => " + primRow[col]);
  435. }
  436. }
  437. }
  438. // Now fill the groups with part data
  439. foreach (DataRow primRow in primsForRegion)
  440. {
  441. try
  442. {
  443. SceneObjectPart prim = null;
  444. string uuid = (string) primRow["UUID"];
  445. string objID = (string) primRow["SceneGroupID"];
  446. if (uuid != objID) //is new SceneObjectGroup ?
  447. {
  448. prim = buildPrim(primRow);
  449. DataRow shapeRow = shapes.Rows.Find(prim.UUID.ToString());
  450. if (shapeRow != null)
  451. {
  452. prim.Shape = buildShape(shapeRow);
  453. }
  454. else
  455. {
  456. m_log.Warn(
  457. "[SQLITE REGION DB]: No shape found for prim in storage, so setting default box shape");
  458. prim.Shape = PrimitiveBaseShape.Default;
  459. }
  460. createdObjects[new UUID(objID)].AddPart(prim);
  461. LoadItems(prim);
  462. }
  463. }
  464. catch (Exception e)
  465. {
  466. m_log.Error("[SQLITE REGION DB]: Failed create prim object in group, exception and data follows");
  467. m_log.Error("[SQLITE REGION DB]: ", e);
  468. foreach (DataColumn col in prims.Columns)
  469. {
  470. m_log.Error("[SQLITE REGION DB]: Col: " + col.ColumnName + " => " + primRow[col]);
  471. }
  472. }
  473. }
  474. }
  475. return retvals;
  476. }
  477. /// <summary>
  478. /// Load in a prim's persisted inventory.
  479. /// </summary>
  480. /// <param name="prim">the prim</param>
  481. private void LoadItems(SceneObjectPart prim)
  482. {
  483. // m_log.DebugFormat("[SQLITE REGION DB]: Loading inventory for {0} {1}", prim.Name, prim.UUID);
  484. DataTable dbItems = ds.Tables["primitems"];
  485. String sql = String.Format("primID = '{0}'", prim.UUID.ToString());
  486. DataRow[] dbItemRows = dbItems.Select(sql);
  487. IList<TaskInventoryItem> inventory = new List<TaskInventoryItem>();
  488. // m_log.DebugFormat(
  489. // "[SQLITE REGION DB]: Found {0} items for {1} {2}", dbItemRows.Length, prim.Name, prim.UUID);
  490. foreach (DataRow row in dbItemRows)
  491. {
  492. TaskInventoryItem item = buildItem(row);
  493. inventory.Add(item);
  494. // m_log.DebugFormat("[SQLITE REGION DB]: Restored item {0} {1}", item.Name, item.ItemID);
  495. }
  496. prim.Inventory.RestoreInventoryItems(inventory);
  497. }
  498. /// <summary>
  499. /// Store a terrain revision in region storage
  500. /// </summary>
  501. /// <param name="ter">terrain heightfield</param>
  502. /// <param name="regionID">region UUID</param>
  503. public void StoreTerrain(double[,] ter, UUID regionID)
  504. {
  505. lock (ds)
  506. {
  507. int revision = Util.UnixTimeSinceEpoch();
  508. // This is added to get rid of the infinitely growing
  509. // terrain databases which negatively impact on SQLite
  510. // over time. Before reenabling this feature there
  511. // needs to be a limitter put on the number of
  512. // revisions in the database, as this old
  513. // implementation is a DOS attack waiting to happen.
  514. using (
  515. SqliteCommand cmd =
  516. new SqliteCommand("delete from terrain where RegionUUID=:RegionUUID and Revision <= :Revision",
  517. m_conn))
  518. {
  519. cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString()));
  520. cmd.Parameters.Add(new SqliteParameter(":Revision", revision));
  521. cmd.ExecuteNonQuery();
  522. }
  523. // the following is an work around for .NET. The perf
  524. // issues associated with it aren't as bad as you think.
  525. m_log.Debug("[SQLITE REGION DB]: Storing terrain revision r" + revision.ToString());
  526. String sql = "insert into terrain(RegionUUID, Revision, Heightfield)" +
  527. " values(:RegionUUID, :Revision, :Heightfield)";
  528. using (SqliteCommand cmd = new SqliteCommand(sql, m_conn))
  529. {
  530. cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString()));
  531. cmd.Parameters.Add(new SqliteParameter(":Revision", revision));
  532. cmd.Parameters.Add(new SqliteParameter(":Heightfield", serializeTerrain(ter)));
  533. cmd.ExecuteNonQuery();
  534. }
  535. }
  536. }
  537. /// <summary>
  538. /// Load the latest terrain revision from region storage
  539. /// </summary>
  540. /// <param name="regionID">the region UUID</param>
  541. /// <returns>Heightfield data</returns>
  542. public double[,] LoadTerrain(UUID regionID)
  543. {
  544. lock (ds)
  545. {
  546. double[,] terret = new double[(int)Constants.RegionSize, (int)Constants.RegionSize];
  547. terret.Initialize();
  548. String sql = "select RegionUUID, Revision, Heightfield from terrain" +
  549. " where RegionUUID=:RegionUUID order by Revision desc";
  550. using (SqliteCommand cmd = new SqliteCommand(sql, m_conn))
  551. {
  552. cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString()));
  553. using (IDataReader row = cmd.ExecuteReader())
  554. {
  555. int rev = 0;
  556. if (row.Read())
  557. {
  558. // TODO: put this into a function
  559. using (MemoryStream str = new MemoryStream((byte[])row["Heightfield"]))
  560. {
  561. using (BinaryReader br = new BinaryReader(str))
  562. {
  563. for (int x = 0; x < (int)Constants.RegionSize; x++)
  564. {
  565. for (int y = 0; y < (int)Constants.RegionSize; y++)
  566. {
  567. terret[x, y] = br.ReadDouble();
  568. }
  569. }
  570. }
  571. }
  572. rev = Convert.ToInt32(row["Revision"]);
  573. }
  574. else
  575. {
  576. m_log.Warn("[SQLITE REGION DB]: No terrain found for region");
  577. return null;
  578. }
  579. m_log.Debug("[SQLITE REGION DB]: Loaded terrain revision r" + rev.ToString());
  580. }
  581. }
  582. return terret;
  583. }
  584. }
  585. public void RemoveLandObject(UUID globalID)
  586. {
  587. lock (ds)
  588. {
  589. // Can't use blanket SQL statements when using SqlAdapters unless you re-read the data into the adapter
  590. // after you're done.
  591. // replaced below code with the SqliteAdapter version.
  592. //using (SqliteCommand cmd = new SqliteCommand("delete from land where UUID=:UUID", m_conn))
  593. //{
  594. // cmd.Parameters.Add(new SqliteParameter(":UUID", globalID.ToString()));
  595. // cmd.ExecuteNonQuery();
  596. //}
  597. //using (SqliteCommand cmd = new SqliteCommand("delete from landaccesslist where LandUUID=:UUID", m_conn))
  598. //{
  599. // cmd.Parameters.Add(new SqliteParameter(":UUID", globalID.ToString()));
  600. // cmd.ExecuteNonQuery();
  601. //}
  602. DataTable land = ds.Tables["land"];
  603. DataTable landaccesslist = ds.Tables["landaccesslist"];
  604. DataRow landRow = land.Rows.Find(globalID.ToString());
  605. if (landRow != null)
  606. {
  607. landRow.Delete();
  608. }
  609. List<DataRow> rowsToDelete = new List<DataRow>();
  610. foreach (DataRow rowToCheck in landaccesslist.Rows)
  611. {
  612. if (rowToCheck["LandUUID"].ToString() == globalID.ToString())
  613. rowsToDelete.Add(rowToCheck);
  614. }
  615. for (int iter = 0; iter < rowsToDelete.Count; iter++)
  616. {
  617. rowsToDelete[iter].Delete();
  618. }
  619. }
  620. Commit();
  621. }
  622. /// <summary>
  623. ///
  624. /// </summary>
  625. /// <param name="parcel"></param>
  626. public void StoreLandObject(ILandObject parcel)
  627. {
  628. lock (ds)
  629. {
  630. DataTable land = ds.Tables["land"];
  631. DataTable landaccesslist = ds.Tables["landaccesslist"];
  632. DataRow landRow = land.Rows.Find(parcel.LandData.GlobalID.ToString());
  633. if (landRow == null)
  634. {
  635. landRow = land.NewRow();
  636. fillLandRow(landRow, parcel.LandData, parcel.RegionUUID);
  637. land.Rows.Add(landRow);
  638. }
  639. else
  640. {
  641. fillLandRow(landRow, parcel.LandData, parcel.RegionUUID);
  642. }
  643. // I know this caused someone issues before, but OpenSim is unusable if we leave this stuff around
  644. //using (SqliteCommand cmd = new SqliteCommand("delete from landaccesslist where LandUUID=:LandUUID", m_conn))
  645. //{
  646. // cmd.Parameters.Add(new SqliteParameter(":LandUUID", parcel.LandData.GlobalID.ToString()));
  647. // cmd.ExecuteNonQuery();
  648. // }
  649. // This is the slower.. but more appropriate thing to do
  650. // We can't modify the table with direct queries before calling Commit() and re-filling them.
  651. List<DataRow> rowsToDelete = new List<DataRow>();
  652. foreach (DataRow rowToCheck in landaccesslist.Rows)
  653. {
  654. if (rowToCheck["LandUUID"].ToString() == parcel.LandData.GlobalID.ToString())
  655. rowsToDelete.Add(rowToCheck);
  656. }
  657. for (int iter = 0; iter < rowsToDelete.Count; iter++)
  658. {
  659. rowsToDelete[iter].Delete();
  660. landaccesslist.Rows.Remove(rowsToDelete[iter]);
  661. }
  662. rowsToDelete.Clear();
  663. foreach (ParcelManager.ParcelAccessEntry entry in parcel.LandData.ParcelAccessList)
  664. {
  665. DataRow newAccessRow = landaccesslist.NewRow();
  666. fillLandAccessRow(newAccessRow, entry, parcel.LandData.GlobalID);
  667. landaccesslist.Rows.Add(newAccessRow);
  668. }
  669. }
  670. Commit();
  671. }
  672. /// <summary>
  673. ///
  674. /// </summary>
  675. /// <param name="regionUUID"></param>
  676. /// <returns></returns>
  677. public List<LandData> LoadLandObjects(UUID regionUUID)
  678. {
  679. List<LandData> landDataForRegion = new List<LandData>();
  680. lock (ds)
  681. {
  682. DataTable land = ds.Tables["land"];
  683. DataTable landaccesslist = ds.Tables["landaccesslist"];
  684. string searchExp = "RegionUUID = '" + regionUUID + "'";
  685. DataRow[] rawDataForRegion = land.Select(searchExp);
  686. foreach (DataRow rawDataLand in rawDataForRegion)
  687. {
  688. LandData newLand = buildLandData(rawDataLand);
  689. string accessListSearchExp = "LandUUID = '" + newLand.GlobalID + "'";
  690. DataRow[] rawDataForLandAccessList = landaccesslist.Select(accessListSearchExp);
  691. foreach (DataRow rawDataLandAccess in rawDataForLandAccessList)
  692. {
  693. newLand.ParcelAccessList.Add(buildLandAccessData(rawDataLandAccess));
  694. }
  695. landDataForRegion.Add(newLand);
  696. }
  697. }
  698. return landDataForRegion;
  699. }
  700. /// <summary>
  701. ///
  702. /// </summary>
  703. public void Commit()
  704. {
  705. //m_log.Debug("[SQLITE]: Starting commit");
  706. lock (ds)
  707. {
  708. primDa.Update(ds, "prims");
  709. shapeDa.Update(ds, "primshapes");
  710. itemsDa.Update(ds, "primitems");
  711. terrainDa.Update(ds, "terrain");
  712. landDa.Update(ds, "land");
  713. landAccessListDa.Update(ds, "landaccesslist");
  714. try
  715. {
  716. regionSettingsDa.Update(ds, "regionsettings");
  717. }
  718. catch (SqliteException SqlEx)
  719. {
  720. throw new Exception(
  721. "There was a SQL error or connection string configuration error when saving the region settings. This could be a bug, it could also happen if ConnectionString is defined in the [DatabaseService] section of StandaloneCommon.ini in the config_include folder. This could also happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. If this is your first time running OpenSimulator, please restart the simulator and bug a developer to fix this!",
  722. SqlEx);
  723. }
  724. ds.AcceptChanges();
  725. }
  726. }
  727. /// <summary>
  728. /// See <see cref="Commit"/>
  729. /// </summary>
  730. public void Shutdown()
  731. {
  732. Commit();
  733. }
  734. /***********************************************************************
  735. *
  736. * Database Definition Functions
  737. *
  738. * This should be db agnostic as we define them in ADO.NET terms
  739. *
  740. **********************************************************************/
  741. protected void CreateDataSetMapping(IDataAdapter da, string tableName)
  742. {
  743. ITableMapping dbMapping = da.TableMappings.Add(tableName, tableName);
  744. foreach (DataColumn col in ds.Tables[tableName].Columns)
  745. {
  746. dbMapping.ColumnMappings.Add(col.ColumnName, col.ColumnName);
  747. }
  748. }
  749. /// <summary>
  750. ///
  751. /// </summary>
  752. /// <param name="dt"></param>
  753. /// <param name="name"></param>
  754. /// <param name="type"></param>
  755. private static void createCol(DataTable dt, string name, Type type)
  756. {
  757. DataColumn col = new DataColumn(name, type);
  758. dt.Columns.Add(col);
  759. }
  760. /// <summary>
  761. /// Creates the "terrain" table
  762. /// </summary>
  763. /// <returns>terrain table DataTable</returns>
  764. private static DataTable createTerrainTable()
  765. {
  766. DataTable terrain = new DataTable("terrain");
  767. createCol(terrain, "RegionUUID", typeof (String));
  768. createCol(terrain, "Revision", typeof (Int32));
  769. createCol(terrain, "Heightfield", typeof (Byte[]));
  770. return terrain;
  771. }
  772. /// <summary>
  773. /// Creates the "prims" table
  774. /// </summary>
  775. /// <returns>prim table DataTable</returns>
  776. private static DataTable createPrimTable()
  777. {
  778. DataTable prims = new DataTable("prims");
  779. createCol(prims, "UUID", typeof (String));
  780. createCol(prims, "RegionUUID", typeof (String));
  781. createCol(prims, "CreationDate", typeof (Int32));
  782. createCol(prims, "Name", typeof (String));
  783. createCol(prims, "SceneGroupID", typeof (String));
  784. // various text fields
  785. createCol(prims, "Text", typeof (String));
  786. createCol(prims, "ColorR", typeof (Int32));
  787. createCol(prims, "ColorG", typeof (Int32));
  788. createCol(prims, "ColorB", typeof (Int32));
  789. createCol(prims, "ColorA", typeof (Int32));
  790. createCol(prims, "Description", typeof (String));
  791. createCol(prims, "SitName", typeof (String));
  792. createCol(prims, "TouchName", typeof (String));
  793. // permissions
  794. createCol(prims, "ObjectFlags", typeof (Int32));
  795. createCol(prims, "CreatorID", typeof (String));
  796. createCol(prims, "OwnerID", typeof (String));
  797. createCol(prims, "GroupID", typeof (String));
  798. createCol(prims, "LastOwnerID", typeof (String));
  799. createCol(prims, "OwnerMask", typeof (Int32));
  800. createCol(prims, "NextOwnerMask", typeof (Int32));
  801. createCol(prims, "GroupMask", typeof (Int32));
  802. createCol(prims, "EveryoneMask", typeof (Int32));
  803. createCol(prims, "BaseMask", typeof (Int32));
  804. // vectors
  805. createCol(prims, "PositionX", typeof (Double));
  806. createCol(prims, "PositionY", typeof (Double));
  807. createCol(prims, "PositionZ", typeof (Double));
  808. createCol(prims, "GroupPositionX", typeof (Double));
  809. createCol(prims, "GroupPositionY", typeof (Double));
  810. createCol(prims, "GroupPositionZ", typeof (Double));
  811. createCol(prims, "VelocityX", typeof (Double));
  812. createCol(prims, "VelocityY", typeof (Double));
  813. createCol(prims, "VelocityZ", typeof (Double));
  814. createCol(prims, "AngularVelocityX", typeof (Double));
  815. createCol(prims, "AngularVelocityY", typeof (Double));
  816. createCol(prims, "AngularVelocityZ", typeof (Double));
  817. createCol(prims, "AccelerationX", typeof (Double));
  818. createCol(prims, "AccelerationY", typeof (Double));
  819. createCol(prims, "AccelerationZ", typeof (Double));
  820. // quaternions
  821. createCol(prims, "RotationX", typeof (Double));
  822. createCol(prims, "RotationY", typeof (Double));
  823. createCol(prims, "RotationZ", typeof (Double));
  824. createCol(prims, "RotationW", typeof (Double));
  825. // sit target
  826. createCol(prims, "SitTargetOffsetX", typeof (Double));
  827. createCol(prims, "SitTargetOffsetY", typeof (Double));
  828. createCol(prims, "SitTargetOffsetZ", typeof (Double));
  829. createCol(prims, "SitTargetOrientW", typeof (Double));
  830. createCol(prims, "SitTargetOrientX", typeof (Double));
  831. createCol(prims, "SitTargetOrientY", typeof (Double));
  832. createCol(prims, "SitTargetOrientZ", typeof (Double));
  833. createCol(prims, "PayPrice", typeof(Int32));
  834. createCol(prims, "PayButton1", typeof(Int32));
  835. createCol(prims, "PayButton2", typeof(Int32));
  836. createCol(prims, "PayButton3", typeof(Int32));
  837. createCol(prims, "PayButton4", typeof(Int32));
  838. createCol(prims, "LoopedSound", typeof(String));
  839. createCol(prims, "LoopedSoundGain", typeof(Double));
  840. createCol(prims, "TextureAnimation", typeof(String));
  841. createCol(prims, "ParticleSystem", typeof(String));
  842. createCol(prims, "OmegaX", typeof(Double));
  843. createCol(prims, "OmegaY", typeof(Double));
  844. createCol(prims, "OmegaZ", typeof(Double));
  845. createCol(prims, "CameraEyeOffsetX", typeof(Double));
  846. createCol(prims, "CameraEyeOffsetY", typeof(Double));
  847. createCol(prims, "CameraEyeOffsetZ", typeof(Double));
  848. createCol(prims, "CameraAtOffsetX", typeof(Double));
  849. createCol(prims, "CameraAtOffsetY", typeof(Double));
  850. createCol(prims, "CameraAtOffsetZ", typeof(Double));
  851. createCol(prims, "ForceMouselook", typeof(Int16));
  852. createCol(prims, "ScriptAccessPin", typeof(Int32));
  853. createCol(prims, "AllowedDrop", typeof(Int16));
  854. createCol(prims, "DieAtEdge", typeof(Int16));
  855. createCol(prims, "SalePrice", typeof(Int32));
  856. createCol(prims, "SaleType", typeof(Int16));
  857. // click action
  858. createCol(prims, "ClickAction", typeof (Byte));
  859. createCol(prims, "Material", typeof(Byte));
  860. createCol(prims, "CollisionSound", typeof(String));
  861. createCol(prims, "CollisionSoundVolume", typeof(Double));
  862. createCol(prims, "VolumeDetect", typeof(Int16));
  863. createCol(prims, "MediaURL", typeof(String));
  864. // Add in contraints
  865. prims.PrimaryKey = new DataColumn[] {prims.Columns["UUID"]};
  866. return prims;
  867. }
  868. /// <summary>
  869. /// Creates "primshapes" table
  870. /// </summary>
  871. /// <returns>shape table DataTable</returns>
  872. private static DataTable createShapeTable()
  873. {
  874. DataTable shapes = new DataTable("primshapes");
  875. createCol(shapes, "UUID", typeof (String));
  876. // shape is an enum
  877. createCol(shapes, "Shape", typeof (Int32));
  878. // vectors
  879. createCol(shapes, "ScaleX", typeof (Double));
  880. createCol(shapes, "ScaleY", typeof (Double));
  881. createCol(shapes, "ScaleZ", typeof (Double));
  882. // paths
  883. createCol(shapes, "PCode", typeof (Int32));
  884. createCol(shapes, "PathBegin", typeof (Int32));
  885. createCol(shapes, "PathEnd", typeof (Int32));
  886. createCol(shapes, "PathScaleX", typeof (Int32));
  887. createCol(shapes, "PathScaleY", typeof (Int32));
  888. createCol(shapes, "PathShearX", typeof (Int32));
  889. createCol(shapes, "PathShearY", typeof (Int32));
  890. createCol(shapes, "PathSkew", typeof (Int32));
  891. createCol(shapes, "PathCurve", typeof (Int32));
  892. createCol(shapes, "PathRadiusOffset", typeof (Int32));
  893. createCol(shapes, "PathRevolutions", typeof (Int32));
  894. createCol(shapes, "PathTaperX", typeof (Int32));
  895. createCol(shapes, "PathTaperY", typeof (Int32));
  896. createCol(shapes, "PathTwist", typeof (Int32));
  897. createCol(shapes, "PathTwistBegin", typeof (Int32));
  898. // profile
  899. createCol(shapes, "ProfileBegin", typeof (Int32));
  900. createCol(shapes, "ProfileEnd", typeof (Int32));
  901. createCol(shapes, "ProfileCurve", typeof (Int32));
  902. createCol(shapes, "ProfileHollow", typeof (Int32));
  903. createCol(shapes, "State", typeof(Int32));
  904. // text TODO: this isn't right, but I'm not sure the right
  905. // way to specify this as a blob atm
  906. createCol(shapes, "Texture", typeof (Byte[]));
  907. createCol(shapes, "ExtraParams", typeof (Byte[]));
  908. createCol(shapes, "Media", typeof(String));
  909. shapes.PrimaryKey = new DataColumn[] {shapes.Columns["UUID"]};
  910. return shapes;
  911. }
  912. /// <summary>
  913. /// creates "primitems" table
  914. /// </summary>
  915. /// <returns>item table DataTable</returns>
  916. private static DataTable createItemsTable()
  917. {
  918. DataTable items = new DataTable("primitems");
  919. createCol(items, "itemID", typeof (String));
  920. createCol(items, "primID", typeof (String));
  921. createCol(items, "assetID", typeof (String));
  922. createCol(items, "parentFolderID", typeof (String));
  923. createCol(items, "invType", typeof (Int32));
  924. createCol(items, "assetType", typeof (Int32));
  925. createCol(items, "name", typeof (String));
  926. createCol(items, "description", typeof (String));
  927. createCol(items, "creationDate", typeof (Int64));
  928. createCol(items, "creatorID", typeof (String));
  929. createCol(items, "ownerID", typeof (String));
  930. createCol(items, "lastOwnerID", typeof (String));
  931. createCol(items, "groupID", typeof (String));
  932. createCol(items, "nextPermissions", typeof (UInt32));
  933. createCol(items, "currentPermissions", typeof (UInt32));
  934. createCol(items, "basePermissions", typeof (UInt32));
  935. createCol(items, "everyonePermissions", typeof (UInt32));
  936. createCol(items, "groupPermissions", typeof (UInt32));
  937. createCol(items, "flags", typeof (UInt32));
  938. items.PrimaryKey = new DataColumn[] { items.Columns["itemID"] };
  939. return items;
  940. }
  941. /// <summary>
  942. /// Creates "land" table
  943. /// </summary>
  944. /// <returns>land table DataTable</returns>
  945. private static DataTable createLandTable()
  946. {
  947. DataTable land = new DataTable("land");
  948. createCol(land, "UUID", typeof (String));
  949. createCol(land, "RegionUUID", typeof (String));
  950. createCol(land, "LocalLandID", typeof (UInt32));
  951. // Bitmap is a byte[512]
  952. createCol(land, "Bitmap", typeof (Byte[]));
  953. createCol(land, "Name", typeof (String));
  954. createCol(land, "Desc", typeof (String));
  955. createCol(land, "OwnerUUID", typeof (String));
  956. createCol(land, "IsGroupOwned", typeof (Boolean));
  957. createCol(land, "Area", typeof (Int32));
  958. createCol(land, "AuctionID", typeof (Int32)); //Unemplemented
  959. createCol(land, "Category", typeof (Int32)); //Enum OpenMetaverse.Parcel.ParcelCategory
  960. createCol(land, "ClaimDate", typeof (Int32));
  961. createCol(land, "ClaimPrice", typeof (Int32));
  962. createCol(land, "GroupUUID", typeof (string));
  963. createCol(land, "SalePrice", typeof (Int32));
  964. createCol(land, "LandStatus", typeof (Int32)); //Enum. OpenMetaverse.Parcel.ParcelStatus
  965. createCol(land, "LandFlags", typeof (UInt32));
  966. createCol(land, "LandingType", typeof (Byte));
  967. createCol(land, "MediaAutoScale", typeof (Byte));
  968. createCol(land, "MediaTextureUUID", typeof (String));
  969. createCol(land, "MediaURL", typeof (String));
  970. createCol(land, "MusicURL", typeof (String));
  971. createCol(land, "PassHours", typeof (Double));
  972. createCol(land, "PassPrice", typeof (UInt32));
  973. createCol(land, "SnapshotUUID", typeof (String));
  974. createCol(land, "UserLocationX", typeof (Double));
  975. createCol(land, "UserLocationY", typeof (Double));
  976. createCol(land, "UserLocationZ", typeof (Double));
  977. createCol(land, "UserLookAtX", typeof (Double));
  978. createCol(land, "UserLookAtY", typeof (Double));
  979. createCol(land, "UserLookAtZ", typeof (Double));
  980. createCol(land, "AuthbuyerID", typeof(String));
  981. createCol(land, "OtherCleanTime", typeof(Int32));
  982. land.PrimaryKey = new DataColumn[] {land.Columns["UUID"]};
  983. return land;
  984. }
  985. /// <summary>
  986. /// create "landaccesslist" table
  987. /// </summary>
  988. /// <returns>Landacceslist DataTable</returns>
  989. private static DataTable createLandAccessListTable()
  990. {
  991. DataTable landaccess = new DataTable("landaccesslist");
  992. createCol(landaccess, "LandUUID", typeof (String));
  993. createCol(landaccess, "AccessUUID", typeof (String));
  994. createCol(landaccess, "Flags", typeof (UInt32));
  995. return landaccess;
  996. }
  997. private static DataTable createRegionSettingsTable()
  998. {
  999. DataTable regionsettings = new DataTable("regionsettings");
  1000. createCol(regionsettings, "regionUUID", typeof(String));
  1001. createCol(regionsettings, "block_terraform", typeof (Int32));
  1002. createCol(regionsettings, "block_fly", typeof (Int32));
  1003. createCol(regionsettings, "allow_damage", typeof (Int32));
  1004. createCol(regionsettings, "restrict_pushing", typeof (Int32));
  1005. createCol(regionsettings, "allow_land_resell", typeof (Int32));
  1006. createCol(regionsettings, "allow_land_join_divide", typeof (Int32));
  1007. createCol(regionsettings, "block_show_in_search", typeof (Int32));
  1008. createCol(regionsettings, "agent_limit", typeof (Int32));
  1009. createCol(regionsettings, "object_bonus", typeof (Double));
  1010. createCol(regionsettings, "maturity", typeof (Int32));
  1011. createCol(regionsettings, "disable_scripts", typeof (Int32));
  1012. createCol(regionsettings, "disable_collisions", typeof (Int32));
  1013. createCol(regionsettings, "disable_physics", typeof (Int32));
  1014. createCol(regionsettings, "terrain_texture_1", typeof(String));
  1015. createCol(regionsettings, "terrain_texture_2", typeof(String));
  1016. createCol(regionsettings, "terrain_texture_3", typeof(String));
  1017. createCol(regionsettings, "terrain_texture_4", typeof(String));
  1018. createCol(regionsettings, "elevation_1_nw", typeof (Double));
  1019. createCol(regionsettings, "elevation_2_nw", typeof (Double));
  1020. createCol(regionsettings, "elevation_1_ne", typeof (Double));
  1021. createCol(regionsettings, "elevation_2_ne", typeof (Double));
  1022. createCol(regionsettings, "elevation_1_se", typeof (Double));
  1023. createCol(regionsettings, "elevation_2_se", typeof (Double));
  1024. createCol(regionsettings, "elevation_1_sw", typeof (Double));
  1025. createCol(regionsettings, "elevation_2_sw", typeof (Double));
  1026. createCol(regionsettings, "water_height", typeof (Double));
  1027. createCol(regionsettings, "terrain_raise_limit", typeof (Double));
  1028. createCol(regionsettings, "terrain_lower_limit", typeof (Double));
  1029. createCol(regionsettings, "use_estate_sun", typeof (Int32));
  1030. createCol(regionsettings, "sandbox", typeof (Int32));
  1031. createCol(regionsettings, "sunvectorx",typeof (Double));
  1032. createCol(regionsettings, "sunvectory",typeof (Double));
  1033. createCol(regionsettings, "sunvectorz",typeof (Double));
  1034. createCol(regionsettings, "fixed_sun", typeof (Int32));
  1035. createCol(regionsettings, "sun_position", typeof (Double));
  1036. createCol(regionsettings, "covenant", typeof(String));
  1037. createCol(regionsettings, "map_tile_ID", typeof(String));
  1038. regionsettings.PrimaryKey = new DataColumn[] { regionsettings.Columns["regionUUID"] };
  1039. return regionsettings;
  1040. }
  1041. /***********************************************************************
  1042. *
  1043. * Convert between ADO.NET <=> OpenSim Objects
  1044. *
  1045. * These should be database independant
  1046. *
  1047. **********************************************************************/
  1048. /// <summary>
  1049. ///
  1050. /// </summary>
  1051. /// <param name="row"></param>
  1052. /// <returns></returns>
  1053. private SceneObjectPart buildPrim(DataRow row)
  1054. {
  1055. // Code commented. Uncomment to test the unit test inline.
  1056. // The unit test mentions this commented code for the purposes
  1057. // of debugging a unit test failure
  1058. // SceneObjectGroup sog = new SceneObjectGroup();
  1059. // SceneObjectPart sop = new SceneObjectPart();
  1060. // sop.LocalId = 1;
  1061. // sop.Name = "object1";
  1062. // sop.Description = "object1";
  1063. // sop.Text = "";
  1064. // sop.SitName = "";
  1065. // sop.TouchName = "";
  1066. // sop.UUID = UUID.Random();
  1067. // sop.Shape = PrimitiveBaseShape.Default;
  1068. // sog.SetRootPart(sop);
  1069. // Add breakpoint in above line. Check sop fields.
  1070. // TODO: this doesn't work yet because something more
  1071. // interesting has to be done to actually get these values
  1072. // back out. Not enough time to figure it out yet.
  1073. SceneObjectPart prim = new SceneObjectPart();
  1074. prim.UUID = new UUID((String) row["UUID"]);
  1075. // explicit conversion of integers is required, which sort
  1076. // of sucks. No idea if there is a shortcut here or not.
  1077. prim.CreationDate = Convert.ToInt32(row["CreationDate"]);
  1078. prim.Name = row["Name"] == DBNull.Value ? string.Empty : (string)row["Name"];
  1079. // various text fields
  1080. prim.Text = (String) row["Text"];
  1081. prim.Color = Color.FromArgb(Convert.ToInt32(row["ColorA"]),
  1082. Convert.ToInt32(row["ColorR"]),
  1083. Convert.ToInt32(row["ColorG"]),
  1084. Convert.ToInt32(row["ColorB"]));
  1085. prim.Description = (String) row["Description"];
  1086. prim.SitName = (String) row["SitName"];
  1087. prim.TouchName = (String) row["TouchName"];
  1088. // permissions
  1089. prim.ObjectFlags = Convert.ToUInt32(row["ObjectFlags"]);
  1090. prim.CreatorIdentification = (String) row["CreatorID"];
  1091. prim.OwnerID = new UUID((String) row["OwnerID"]);
  1092. prim.GroupID = new UUID((String) row["GroupID"]);
  1093. prim.LastOwnerID = new UUID((String) row["LastOwnerID"]);
  1094. prim.OwnerMask = Convert.ToUInt32(row["OwnerMask"]);
  1095. prim.NextOwnerMask = Convert.ToUInt32(row["NextOwnerMask"]);
  1096. prim.GroupMask = Convert.ToUInt32(row["GroupMask"]);
  1097. prim.EveryoneMask = Convert.ToUInt32(row["EveryoneMask"]);
  1098. prim.BaseMask = Convert.ToUInt32(row["BaseMask"]);
  1099. // vectors
  1100. prim.OffsetPosition = new Vector3(
  1101. Convert.ToSingle(row["PositionX"]),
  1102. Convert.ToSingle(row["PositionY"]),
  1103. Convert.ToSingle(row["PositionZ"])
  1104. );
  1105. prim.GroupPosition = new Vector3(
  1106. Convert.ToSingle(row["GroupPositionX"]),
  1107. Convert.ToSingle(row["GroupPositionY"]),
  1108. Convert.ToSingle(row["GroupPositionZ"])
  1109. );
  1110. prim.Velocity = new Vector3(
  1111. Convert.ToSingle(row["VelocityX"]),
  1112. Convert.ToSingle(row["VelocityY"]),
  1113. Convert.ToSingle(row["VelocityZ"])
  1114. );
  1115. prim.AngularVelocity = new Vector3(
  1116. Convert.ToSingle(row["AngularVelocityX"]),
  1117. Convert.ToSingle(row["AngularVelocityY"]),
  1118. Convert.ToSingle(row["AngularVelocityZ"])
  1119. );
  1120. prim.Acceleration = new Vector3(
  1121. Convert.ToSingle(row["AccelerationX"]),
  1122. Convert.ToSingle(row["AccelerationY"]),
  1123. Convert.ToSingle(row["AccelerationZ"])
  1124. );
  1125. // quaternions
  1126. prim.RotationOffset = new Quaternion(
  1127. Convert.ToSingle(row["RotationX"]),
  1128. Convert.ToSingle(row["RotationY"]),
  1129. Convert.ToSingle(row["RotationZ"]),
  1130. Convert.ToSingle(row["RotationW"])
  1131. );
  1132. prim.SitTargetPositionLL = new Vector3(
  1133. Convert.ToSingle(row["SitTargetOffsetX"]),
  1134. Convert.ToSingle(row["SitTargetOffsetY"]),
  1135. Convert.ToSingle(row["SitTargetOffsetZ"]));
  1136. prim.SitTargetOrientationLL = new Quaternion(
  1137. Convert.ToSingle(
  1138. row["SitTargetOrientX"]),
  1139. Convert.ToSingle(
  1140. row["SitTargetOrientY"]),
  1141. Convert.ToSingle(
  1142. row["SitTargetOrientZ"]),
  1143. Convert.ToSingle(
  1144. row["SitTargetOrientW"]));
  1145. prim.ClickAction = Convert.ToByte(row["ClickAction"]);
  1146. prim.PayPrice[0] = Convert.ToInt32(row["PayPrice"]);
  1147. prim.PayPrice[1] = Convert.ToInt32(row["PayButton1"]);
  1148. prim.PayPrice[2] = Convert.ToInt32(row["PayButton2"]);
  1149. prim.PayPrice[3] = Convert.ToInt32(row["PayButton3"]);
  1150. prim.PayPrice[4] = Convert.ToInt32(row["PayButton4"]);
  1151. prim.Sound = new UUID(row["LoopedSound"].ToString());
  1152. prim.SoundGain = Convert.ToSingle(row["LoopedSoundGain"]);
  1153. prim.SoundFlags = 1; // If it's persisted at all, it's looped
  1154. if (!row.IsNull("TextureAnimation"))
  1155. prim.TextureAnimation = Convert.FromBase64String(row["TextureAnimation"].ToString());
  1156. if (!row.IsNull("ParticleSystem"))
  1157. prim.ParticleSystem = Convert.FromBase64String(row["ParticleSystem"].ToString());
  1158. prim.AngularVelocity = new Vector3(
  1159. Convert.ToSingle(row["OmegaX"]),
  1160. Convert.ToSingle(row["OmegaY"]),
  1161. Convert.ToSingle(row["OmegaZ"])
  1162. );
  1163. prim.SetCameraEyeOffset(new Vector3(
  1164. Convert.ToSingle(row["CameraEyeOffsetX"]),
  1165. Convert.ToSingle(row["CameraEyeOffsetY"]),
  1166. Convert.ToSingle(row["CameraEyeOffsetZ"])
  1167. ));
  1168. prim.SetCameraAtOffset(new Vector3(
  1169. Convert.ToSingle(row["CameraAtOffsetX"]),
  1170. Convert.ToSingle(row["CameraAtOffsetY"]),
  1171. Convert.ToSingle(row["CameraAtOffsetZ"])
  1172. ));
  1173. if (Convert.ToInt16(row["ForceMouselook"]) != 0)
  1174. prim.SetForceMouselook(true);
  1175. prim.ScriptAccessPin = Convert.ToInt32(row["ScriptAccessPin"]);
  1176. if (Convert.ToInt16(row["AllowedDrop"]) != 0)
  1177. prim.AllowedDrop = true;
  1178. if (Convert.ToInt16(row["DieAtEdge"]) != 0)
  1179. prim.DIE_AT_EDGE = true;
  1180. prim.SalePrice = Convert.ToInt32(row["SalePrice"]);
  1181. prim.ObjectSaleType = Convert.ToByte(row["SaleType"]);
  1182. prim.Material = Convert.ToByte(row["Material"]);
  1183. prim.CollisionSound = new UUID(row["CollisionSound"].ToString());
  1184. prim.CollisionSoundVolume = Convert.ToSingle(row["CollisionSoundVolume"]);
  1185. if (Convert.ToInt16(row["VolumeDetect"]) != 0)
  1186. prim.VolumeDetectActive = true;
  1187. if (!(row["MediaURL"] is System.DBNull))
  1188. {
  1189. //m_log.DebugFormat("[SQLITE]: MediaUrl type [{0}]", row["MediaURL"].GetType());
  1190. prim.MediaUrl = (string)row["MediaURL"];
  1191. }
  1192. return prim;
  1193. }
  1194. /// <summary>
  1195. /// Build a prim inventory item from the persisted data.
  1196. /// </summary>
  1197. /// <param name="row"></param>
  1198. /// <returns></returns>
  1199. private static TaskInventoryItem buildItem(DataRow row)
  1200. {
  1201. TaskInventoryItem taskItem = new TaskInventoryItem();
  1202. taskItem.ItemID = new UUID((String)row["itemID"]);
  1203. taskItem.ParentPartID = new UUID((String)row["primID"]);
  1204. taskItem.AssetID = new UUID((String)row["assetID"]);
  1205. taskItem.ParentID = new UUID((String)row["parentFolderID"]);
  1206. taskItem.InvType = Convert.ToInt32(row["invType"]);
  1207. taskItem.Type = Convert.ToInt32(row["assetType"]);
  1208. taskItem.Name = (String)row["name"];
  1209. taskItem.Description = (String)row["description"];
  1210. taskItem.CreationDate = Convert.ToUInt32(row["creationDate"]);
  1211. taskItem.CreatorIdentification = (String)row["creatorID"];
  1212. taskItem.OwnerID = new UUID((String)row["ownerID"]);
  1213. taskItem.LastOwnerID = new UUID((String)row["lastOwnerID"]);
  1214. taskItem.GroupID = new UUID((String)row["groupID"]);
  1215. taskItem.NextPermissions = Convert.ToUInt32(row["nextPermissions"]);
  1216. taskItem.CurrentPermissions = Convert.ToUInt32(row["currentPermissions"]);
  1217. taskItem.BasePermissions = Convert.ToUInt32(row["basePermissions"]);
  1218. taskItem.EveryonePermissions = Convert.ToUInt32(row["everyonePermissions"]);
  1219. taskItem.GroupPermissions = Convert.ToUInt32(row["groupPermissions"]);
  1220. taskItem.Flags = Convert.ToUInt32(row["flags"]);
  1221. return taskItem;
  1222. }
  1223. /// <summary>
  1224. /// Build a Land Data from the persisted data.
  1225. /// </summary>
  1226. /// <param name="row"></param>
  1227. /// <returns></returns>
  1228. private LandData buildLandData(DataRow row)
  1229. {
  1230. LandData newData = new LandData();
  1231. newData.GlobalID = new UUID((String) row["UUID"]);
  1232. newData.LocalID = Convert.ToInt32(row["LocalLandID"]);
  1233. // Bitmap is a byte[512]
  1234. newData.Bitmap = (Byte[]) row["Bitmap"];
  1235. newData.Name = (String) row["Name"];
  1236. newData.Description = (String) row["Desc"];
  1237. newData.OwnerID = (UUID)(String) row["OwnerUUID"];
  1238. newData.IsGroupOwned = (Boolean) row["IsGroupOwned"];
  1239. newData.Area = Convert.ToInt32(row["Area"]);
  1240. newData.AuctionID = Convert.ToUInt32(row["AuctionID"]); //Unemplemented
  1241. newData.Category = (ParcelCategory) Convert.ToInt32(row["Category"]);
  1242. //Enum OpenMetaverse.Parcel.ParcelCategory
  1243. newData.ClaimDate = Convert.ToInt32(row["ClaimDate"]);
  1244. newData.ClaimPrice = Convert.ToInt32(row["ClaimPrice"]);
  1245. newData.GroupID = new UUID((String) row["GroupUUID"]);
  1246. newData.SalePrice = Convert.ToInt32(row["SalePrice"]);
  1247. newData.Status = (ParcelStatus) Convert.ToInt32(row["LandStatus"]);
  1248. //Enum. OpenMetaverse.Parcel.ParcelStatus
  1249. newData.Flags = Convert.ToUInt32(row["LandFlags"]);
  1250. newData.LandingType = (Byte) row["LandingType"];
  1251. newData.MediaAutoScale = (Byte) row["MediaAutoScale"];
  1252. newData.MediaID = new UUID((String) row["MediaTextureUUID"]);
  1253. newData.MediaURL = (String) row["MediaURL"];
  1254. newData.MusicURL = (String) row["MusicURL"];
  1255. newData.PassHours = Convert.ToSingle(row["PassHours"]);
  1256. newData.PassPrice = Convert.ToInt32(row["PassPrice"]);
  1257. newData.SnapshotID = (UUID)(String) row["SnapshotUUID"];
  1258. try
  1259. {
  1260. newData.UserLocation =
  1261. new Vector3(Convert.ToSingle(row["UserLocationX"]), Convert.ToSingle(row["UserLocationY"]),
  1262. Convert.ToSingle(row["UserLocationZ"]));
  1263. newData.UserLookAt =
  1264. new Vector3(Convert.ToSingle(row["UserLookAtX"]), Convert.ToSingle(row["UserLookAtY"]),
  1265. Convert.ToSingle(row["UserLookAtZ"]));
  1266. }
  1267. catch (InvalidCastException)
  1268. {
  1269. m_log.ErrorFormat("[SQLITE REGION DB]: unable to get parcel telehub settings for {1}", newData.Name);
  1270. newData.UserLocation = Vector3.Zero;
  1271. newData.UserLookAt = Vector3.Zero;
  1272. }
  1273. newData.ParcelAccessList = new List<ParcelManager.ParcelAccessEntry>();
  1274. UUID authBuyerID = UUID.Zero;
  1275. UUID.TryParse((string)row["AuthbuyerID"], out authBuyerID);
  1276. newData.OtherCleanTime = Convert.ToInt32(row["OtherCleanTime"]);
  1277. return newData;
  1278. }
  1279. private RegionSettings buildRegionSettings(DataRow row)
  1280. {
  1281. RegionSettings newSettings = new RegionSettings();
  1282. newSettings.RegionUUID = new UUID((string) row["regionUUID"]);
  1283. newSettings.BlockTerraform = Convert.ToBoolean(row["block_terraform"]);
  1284. newSettings.AllowDamage = Convert.ToBoolean(row["allow_damage"]);
  1285. newSettings.BlockFly = Convert.ToBoolean(row["block_fly"]);
  1286. newSettings.RestrictPushing = Convert.ToBoolean(row["restrict_pushing"]);
  1287. newSettings.AllowLandResell = Convert.ToBoolean(row["allow_land_resell"]);
  1288. newSettings.AllowLandJoinDivide = Convert.ToBoolean(row["allow_land_join_divide"]);
  1289. newSettings.BlockShowInSearch = Convert.ToBoolean(row["block_show_in_search"]);
  1290. newSettings.AgentLimit = Convert.ToInt32(row["agent_limit"]);
  1291. newSettings.ObjectBonus = Convert.ToDouble(row["object_bonus"]);
  1292. newSettings.Maturity = Convert.ToInt32(row["maturity"]);
  1293. newSettings.DisableScripts = Convert.ToBoolean(row["disable_scripts"]);
  1294. newSettings.DisableCollisions = Convert.ToBoolean(row["disable_collisions"]);
  1295. newSettings.DisablePhysics = Convert.ToBoolean(row["disable_physics"]);
  1296. newSettings.TerrainTexture1 = new UUID((String) row["terrain_texture_1"]);
  1297. newSettings.TerrainTexture2 = new UUID((String) row["terrain_texture_2"]);
  1298. newSettings.TerrainTexture3 = new UUID((String) row["terrain_texture_3"]);
  1299. newSettings.TerrainTexture4 = new UUID((String) row["terrain_texture_4"]);
  1300. newSettings.Elevation1NW = Convert.ToDouble(row["elevation_1_nw"]);
  1301. newSettings.Elevation2NW = Convert.ToDouble(row["elevation_2_nw"]);
  1302. newSettings.Elevation1NE = Convert.ToDouble(row["elevation_1_ne"]);
  1303. newSettings.Elevation2NE = Convert.ToDouble(row["elevation_2_ne"]);
  1304. newSettings.Elevation1SE = Convert.ToDouble(row["elevation_1_se"]);
  1305. newSettings.Elevation2SE = Convert.ToDouble(row["elevation_2_se"]);
  1306. newSettings.Elevation1SW = Convert.ToDouble(row["elevation_1_sw"]);
  1307. newSettings.Elevation2SW = Convert.ToDouble(row["elevation_2_sw"]);
  1308. newSettings.WaterHeight = Convert.ToDouble(row["water_height"]);
  1309. newSettings.TerrainRaiseLimit = Convert.ToDouble(row["terrain_raise_limit"]);
  1310. newSettings.TerrainLowerLimit = Convert.ToDouble(row["terrain_lower_limit"]);
  1311. newSettings.UseEstateSun = Convert.ToBoolean(row["use_estate_sun"]);
  1312. newSettings.Sandbox = Convert.ToBoolean(row["sandbox"]);
  1313. newSettings.SunVector = new Vector3 (
  1314. Convert.ToSingle(row["sunvectorx"]),
  1315. Convert.ToSingle(row["sunvectory"]),
  1316. Convert.ToSingle(row["sunvectorz"])
  1317. );
  1318. newSettings.FixedSun = Convert.ToBoolean(row["fixed_sun"]);
  1319. newSettings.SunPosition = Convert.ToDouble(row["sun_position"]);
  1320. newSettings.Covenant = new UUID((String) row["covenant"]);
  1321. newSettings.TerrainImageID = new UUID((String)row["map_tile_ID"]);
  1322. return newSettings;
  1323. }
  1324. /// <summary>
  1325. /// Build a land access entry from the persisted data.
  1326. /// </summary>
  1327. /// <param name="row"></param>
  1328. /// <returns></returns>
  1329. private static ParcelManager.ParcelAccessEntry buildLandAccessData(DataRow row)
  1330. {
  1331. ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry();
  1332. entry.AgentID = new UUID((string) row["AccessUUID"]);
  1333. entry.Flags = (AccessList) row["Flags"];
  1334. entry.Time = new DateTime();
  1335. return entry;
  1336. }
  1337. /// <summary>
  1338. ///
  1339. /// </summary>
  1340. /// <param name="val"></param>
  1341. /// <returns></returns>
  1342. private static Array serializeTerrain(double[,] val)
  1343. {
  1344. MemoryStream str = new MemoryStream(((int)Constants.RegionSize * (int)Constants.RegionSize) *sizeof (double));
  1345. BinaryWriter bw = new BinaryWriter(str);
  1346. // TODO: COMPATIBILITY - Add byte-order conversions
  1347. for (int x = 0; x < (int)Constants.RegionSize; x++)
  1348. for (int y = 0; y < (int)Constants.RegionSize; y++)
  1349. bw.Write(val[x, y]);
  1350. return str.ToArray();
  1351. }
  1352. // private void fillTerrainRow(DataRow row, UUID regionUUID, int rev, double[,] val)
  1353. // {
  1354. // row["RegionUUID"] = regionUUID;
  1355. // row["Revision"] = rev;
  1356. // MemoryStream str = new MemoryStream(((int)Constants.RegionSize * (int)Constants.RegionSize)*sizeof (double));
  1357. // BinaryWriter bw = new BinaryWriter(str);
  1358. // // TODO: COMPATIBILITY - Add byte-order conversions
  1359. // for (int x = 0; x < (int)Constants.RegionSize; x++)
  1360. // for (int y = 0; y < (int)Constants.RegionSize; y++)
  1361. // bw.Write(val[x, y]);
  1362. // row["Heightfield"] = str.ToArray();
  1363. // }
  1364. /// <summary>
  1365. ///
  1366. /// </summary>
  1367. /// <param name="row"></param>
  1368. /// <param name="prim"></param>
  1369. /// <param name="sceneGroupID"></param>
  1370. /// <param name="regionUUID"></param>
  1371. private static void fillPrimRow(DataRow row, SceneObjectPart prim, UUID sceneGroupID, UUID regionUUID)
  1372. {
  1373. row["UUID"] = prim.UUID.ToString();
  1374. row["RegionUUID"] = regionUUID.ToString();
  1375. row["CreationDate"] = prim.CreationDate;
  1376. row["Name"] = prim.Name;
  1377. row["SceneGroupID"] = sceneGroupID.ToString();
  1378. // the UUID of the root part for this SceneObjectGroup
  1379. // various text fields
  1380. row["Text"] = prim.Text;
  1381. row["Description"] = prim.Description;
  1382. row["SitName"] = prim.SitName;
  1383. row["TouchName"] = prim.TouchName;
  1384. // permissions
  1385. row["ObjectFlags"] = prim.ObjectFlags;
  1386. row["CreatorID"] = prim.CreatorIdentification.ToString();
  1387. row["OwnerID"] = prim.OwnerID.ToString();
  1388. row["GroupID"] = prim.GroupID.ToString();
  1389. row["LastOwnerID"] = prim.LastOwnerID.ToString();
  1390. row["OwnerMask"] = prim.OwnerMask;
  1391. row["NextOwnerMask"] = prim.NextOwnerMask;
  1392. row["GroupMask"] = prim.GroupMask;
  1393. row["EveryoneMask"] = prim.EveryoneMask;
  1394. row["BaseMask"] = prim.BaseMask;
  1395. // vectors
  1396. row["PositionX"] = prim.OffsetPosition.X;
  1397. row["PositionY"] = prim.OffsetPosition.Y;
  1398. row["PositionZ"] = prim.OffsetPosition.Z;
  1399. row["GroupPositionX"] = prim.GroupPosition.X;
  1400. row["GroupPositionY"] = prim.GroupPosition.Y;
  1401. row["GroupPositionZ"] = prim.GroupPosition.Z;
  1402. row["VelocityX"] = prim.Velocity.X;
  1403. row["VelocityY"] = prim.Velocity.Y;
  1404. row["VelocityZ"] = prim.Velocity.Z;
  1405. row["AngularVelocityX"] = prim.AngularVelocity.X;
  1406. row["AngularVelocityY"] = prim.AngularVelocity.Y;
  1407. row["AngularVelocityZ"] = prim.AngularVelocity.Z;
  1408. row["AccelerationX"] = prim.Acceleration.X;
  1409. row["AccelerationY"] = prim.Acceleration.Y;
  1410. row["AccelerationZ"] = prim.Acceleration.Z;
  1411. // quaternions
  1412. row["RotationX"] = prim.RotationOffset.X;
  1413. row["RotationY"] = prim.RotationOffset.Y;
  1414. row["RotationZ"] = prim.RotationOffset.Z;
  1415. row["RotationW"] = prim.RotationOffset.W;
  1416. // Sit target
  1417. Vector3 sitTargetPos = prim.SitTargetPositionLL;
  1418. row["SitTargetOffsetX"] = sitTargetPos.X;
  1419. row["SitTargetOffsetY"] = sitTargetPos.Y;
  1420. row["SitTargetOffsetZ"] = sitTargetPos.Z;
  1421. Quaternion sitTargetOrient = prim.SitTargetOrientationLL;
  1422. row["SitTargetOrientW"] = sitTargetOrient.W;
  1423. row["SitTargetOrientX"] = sitTargetOrient.X;
  1424. row["SitTargetOrientY"] = sitTargetOrient.Y;
  1425. row["SitTargetOrientZ"] = sitTargetOrient.Z;
  1426. row["ColorR"] = Convert.ToInt32(prim.Color.R);
  1427. row["ColorG"] = Convert.ToInt32(prim.Color.G);
  1428. row["ColorB"] = Convert.ToInt32(prim.Color.B);
  1429. row["ColorA"] = Convert.ToInt32(prim.Color.A);
  1430. row["PayPrice"] = prim.PayPrice[0];
  1431. row["PayButton1"] = prim.PayPrice[1];
  1432. row["PayButton2"] = prim.PayPrice[2];
  1433. row["PayButton3"] = prim.PayPrice[3];
  1434. row["PayButton4"] = prim.PayPrice[4];
  1435. row["TextureAnimation"] = Convert.ToBase64String(prim.TextureAnimation);
  1436. row["ParticleSystem"] = Convert.ToBase64String(prim.ParticleSystem);
  1437. row["OmegaX"] = prim.AngularVelocity.X;
  1438. row["OmegaY"] = prim.AngularVelocity.Y;
  1439. row["OmegaZ"] = prim.AngularVelocity.Z;
  1440. row["CameraEyeOffsetX"] = prim.GetCameraEyeOffset().X;
  1441. row["CameraEyeOffsetY"] = prim.GetCameraEyeOffset().Y;
  1442. row["CameraEyeOffsetZ"] = prim.GetCameraEyeOffset().Z;
  1443. row["CameraAtOffsetX"] = prim.GetCameraAtOffset().X;
  1444. row["CameraAtOffsetY"] = prim.GetCameraAtOffset().Y;
  1445. row["CameraAtOffsetZ"] = prim.GetCameraAtOffset().Z;
  1446. if ((prim.SoundFlags & 1) != 0) // Looped
  1447. {
  1448. row["LoopedSound"] = prim.Sound.ToString();
  1449. row["LoopedSoundGain"] = prim.SoundGain;
  1450. }
  1451. else
  1452. {
  1453. row["LoopedSound"] = UUID.Zero.ToString();
  1454. row["LoopedSoundGain"] = 0.0f;
  1455. }
  1456. if (prim.GetForceMouselook())
  1457. row["ForceMouselook"] = 1;
  1458. else
  1459. row["ForceMouselook"] = 0;
  1460. row["ScriptAccessPin"] = prim.ScriptAccessPin;
  1461. if (prim.AllowedDrop)
  1462. row["AllowedDrop"] = 1;
  1463. else
  1464. row["AllowedDrop"] = 0;
  1465. if (prim.DIE_AT_EDGE)
  1466. row["DieAtEdge"] = 1;
  1467. else
  1468. row["DieAtEdge"] = 0;
  1469. row["SalePrice"] = prim.SalePrice;
  1470. row["SaleType"] = Convert.ToInt16(prim.ObjectSaleType);
  1471. // click action
  1472. row["ClickAction"] = prim.ClickAction;
  1473. row["SalePrice"] = prim.SalePrice;
  1474. row["Material"] = prim.Material;
  1475. row["CollisionSound"] = prim.CollisionSound.ToString();
  1476. row["CollisionSoundVolume"] = prim.CollisionSoundVolume;
  1477. if (prim.VolumeDetectActive)
  1478. row["VolumeDetect"] = 1;
  1479. else
  1480. row["VolumeDetect"] = 0;
  1481. row["MediaURL"] = prim.MediaUrl;
  1482. }
  1483. /// <summary>
  1484. ///
  1485. /// </summary>
  1486. /// <param name="row"></param>
  1487. /// <param name="taskItem"></param>
  1488. private static void fillItemRow(DataRow row, TaskInventoryItem taskItem)
  1489. {
  1490. row["itemID"] = taskItem.ItemID.ToString();
  1491. row["primID"] = taskItem.ParentPartID.ToString();
  1492. row["assetID"] = taskItem.AssetID.ToString();
  1493. row["parentFolderID"] = taskItem.ParentID.ToString();
  1494. row["invType"] = taskItem.InvType;
  1495. row["assetType"] = taskItem.Type;
  1496. row["name"] = taskItem.Name;
  1497. row["description"] = taskItem.Description;
  1498. row["creationDate"] = taskItem.CreationDate;
  1499. row["creatorID"] = taskItem.CreatorIdentification.ToString();
  1500. row["ownerID"] = taskItem.OwnerID.ToString();
  1501. row["lastOwnerID"] = taskItem.LastOwnerID.ToString();
  1502. row["groupID"] = taskItem.GroupID.ToString();
  1503. row["nextPermissions"] = taskItem.NextPermissions;
  1504. row["currentPermissions"] = taskItem.CurrentPermissions;
  1505. row["basePermissions"] = taskItem.BasePermissions;
  1506. row["everyonePermissions"] = taskItem.EveryonePermissions;
  1507. row["groupPermissions"] = taskItem.GroupPermissions;
  1508. row["flags"] = taskItem.Flags;
  1509. }
  1510. /// <summary>
  1511. ///
  1512. /// </summary>
  1513. /// <param name="row"></param>
  1514. /// <param name="land"></param>
  1515. /// <param name="regionUUID"></param>
  1516. private static void fillLandRow(DataRow row, LandData land, UUID regionUUID)
  1517. {
  1518. row["UUID"] = land.GlobalID.ToString();
  1519. row["RegionUUID"] = regionUUID.ToString();
  1520. row["LocalLandID"] = land.LocalID;
  1521. // Bitmap is a byte[512]
  1522. row["Bitmap"] = land.Bitmap;
  1523. row["Name"] = land.Name;
  1524. row["Desc"] = land.Description;
  1525. row["OwnerUUID"] = land.OwnerID.ToString();
  1526. row["IsGroupOwned"] = land.IsGroupOwned;
  1527. row["Area"] = land.Area;
  1528. row["AuctionID"] = land.AuctionID; //Unemplemented
  1529. row["Category"] = land.Category; //Enum OpenMetaverse.Parcel.ParcelCategory
  1530. row["ClaimDate"] = land.ClaimDate;
  1531. row["ClaimPrice"] = land.ClaimPrice;
  1532. row["GroupUUID"] = land.GroupID.ToString();
  1533. row["SalePrice"] = land.SalePrice;
  1534. row["LandStatus"] = land.Status; //Enum. OpenMetaverse.Parcel.ParcelStatus
  1535. row["LandFlags"] = land.Flags;
  1536. row["LandingType"] = land.LandingType;
  1537. row["MediaAutoScale"] = land.MediaAutoScale;
  1538. row["MediaTextureUUID"] = land.MediaID.ToString();
  1539. row["MediaURL"] = land.MediaURL;
  1540. row["MusicURL"] = land.MusicURL;
  1541. row["PassHours"] = land.PassHours;
  1542. row["PassPrice"] = land.PassPrice;
  1543. row["SnapshotUUID"] = land.SnapshotID.ToString();
  1544. row["UserLocationX"] = land.UserLocation.X;
  1545. row["UserLocationY"] = land.UserLocation.Y;
  1546. row["UserLocationZ"] = land.UserLocation.Z;
  1547. row["UserLookAtX"] = land.UserLookAt.X;
  1548. row["UserLookAtY"] = land.UserLookAt.Y;
  1549. row["UserLookAtZ"] = land.UserLookAt.Z;
  1550. row["AuthbuyerID"] = land.AuthBuyerID.ToString();
  1551. row["OtherCleanTime"] = land.OtherCleanTime;
  1552. row["MediaType"] = land.MediaType;
  1553. row["MediaDescription"] = land.MediaDescription;
  1554. row["MediaSize"] = land.MediaWidth.ToString() + "," + land.MediaHeight.ToString();
  1555. row["MediaLoop"] = land.MediaLoop.ToString();
  1556. row["ObscureMusic"] = land.ObscureMusic.ToString();
  1557. row["ObscureMedia"] = land.ObscureMedia.ToString();
  1558. }
  1559. /// <summary>
  1560. ///
  1561. /// </summary>
  1562. /// <param name="row"></param>
  1563. /// <param name="entry"></param>
  1564. /// <param name="parcelID"></param>
  1565. private static void fillLandAccessRow(DataRow row, ParcelManager.ParcelAccessEntry entry, UUID parcelID)
  1566. {
  1567. row["LandUUID"] = parcelID.ToString();
  1568. row["AccessUUID"] = entry.AgentID.ToString();
  1569. row["Flags"] = entry.Flags;
  1570. }
  1571. private static void fillRegionSettingsRow(DataRow row, RegionSettings settings)
  1572. {
  1573. row["regionUUID"] = settings.RegionUUID.ToString();
  1574. row["block_terraform"] = settings.BlockTerraform;
  1575. row["block_fly"] = settings.BlockFly;
  1576. row["allow_damage"] = settings.AllowDamage;
  1577. row["restrict_pushing"] = settings.RestrictPushing;
  1578. row["allow_land_resell"] = settings.AllowLandResell;
  1579. row["allow_land_join_divide"] = settings.AllowLandJoinDivide;
  1580. row["block_show_in_search"] = settings.BlockShowInSearch;
  1581. row["agent_limit"] = settings.AgentLimit;
  1582. row["object_bonus"] = settings.ObjectBonus;
  1583. row["maturity"] = settings.Maturity;
  1584. row["disable_scripts"] = settings.DisableScripts;
  1585. row["disable_collisions"] = settings.DisableCollisions;
  1586. row["disable_physics"] = settings.DisablePhysics;
  1587. row["terrain_texture_1"] = settings.TerrainTexture1.ToString();
  1588. row["terrain_texture_2"] = settings.TerrainTexture2.ToString();
  1589. row["terrain_texture_3"] = settings.TerrainTexture3.ToString();
  1590. row["terrain_texture_4"] = settings.TerrainTexture4.ToString();
  1591. row["elevation_1_nw"] = settings.Elevation1NW;
  1592. row["elevation_2_nw"] = settings.Elevation2NW;
  1593. row["elevation_1_ne"] = settings.Elevation1NE;
  1594. row["elevation_2_ne"] = settings.Elevation2NE;
  1595. row["elevation_1_se"] = settings.Elevation1SE;
  1596. row["elevation_2_se"] = settings.Elevation2SE;
  1597. row["elevation_1_sw"] = settings.Elevation1SW;
  1598. row["elevation_2_sw"] = settings.Elevation2SW;
  1599. row["water_height"] = settings.WaterHeight;
  1600. row["terrain_raise_limit"] = settings.TerrainRaiseLimit;
  1601. row["terrain_lower_limit"] = settings.TerrainLowerLimit;
  1602. row["use_estate_sun"] = settings.UseEstateSun;
  1603. row["Sandbox"] = settings.Sandbox; // database uses upper case S for sandbox
  1604. row["sunvectorx"] = settings.SunVector.X;
  1605. row["sunvectory"] = settings.SunVector.Y;
  1606. row["sunvectorz"] = settings.SunVector.Z;
  1607. row["fixed_sun"] = settings.FixedSun;
  1608. row["sun_position"] = settings.SunPosition;
  1609. row["covenant"] = settings.Covenant.ToString();
  1610. row["map_tile_ID"] = settings.TerrainImageID.ToString();
  1611. }
  1612. /// <summary>
  1613. ///
  1614. /// </summary>
  1615. /// <param name="row"></param>
  1616. /// <returns></returns>
  1617. private PrimitiveBaseShape buildShape(DataRow row)
  1618. {
  1619. PrimitiveBaseShape s = new PrimitiveBaseShape();
  1620. s.Scale = new Vector3(
  1621. Convert.ToSingle(row["ScaleX"]),
  1622. Convert.ToSingle(row["ScaleY"]),
  1623. Convert.ToSingle(row["ScaleZ"])
  1624. );
  1625. // paths
  1626. s.PCode = Convert.ToByte(row["PCode"]);
  1627. s.PathBegin = Convert.ToUInt16(row["PathBegin"]);
  1628. s.PathEnd = Convert.ToUInt16(row["PathEnd"]);
  1629. s.PathScaleX = Convert.ToByte(row["PathScaleX"]);
  1630. s.PathScaleY = Convert.ToByte(row["PathScaleY"]);
  1631. s.PathShearX = Convert.ToByte(row["PathShearX"]);
  1632. s.PathShearY = Convert.ToByte(row["PathShearY"]);
  1633. s.PathSkew = Convert.ToSByte(row["PathSkew"]);
  1634. s.PathCurve = Convert.ToByte(row["PathCurve"]);
  1635. s.PathRadiusOffset = Convert.ToSByte(row["PathRadiusOffset"]);
  1636. s.PathRevolutions = Convert.ToByte(row["PathRevolutions"]);
  1637. s.PathTaperX = Convert.ToSByte(row["PathTaperX"]);
  1638. s.PathTaperY = Convert.ToSByte(row["PathTaperY"]);
  1639. s.PathTwist = Convert.ToSByte(row["PathTwist"]);
  1640. s.PathTwistBegin = Convert.ToSByte(row["PathTwistBegin"]);
  1641. // profile
  1642. s.ProfileBegin = Convert.ToUInt16(row["ProfileBegin"]);
  1643. s.ProfileEnd = Convert.ToUInt16(row["ProfileEnd"]);
  1644. s.ProfileCurve = Convert.ToByte(row["ProfileCurve"]);
  1645. s.ProfileHollow = Convert.ToUInt16(row["ProfileHollow"]);
  1646. s.State = Convert.ToByte(row["State"]);
  1647. byte[] textureEntry = (byte[])row["Texture"];
  1648. s.TextureEntry = textureEntry;
  1649. s.ExtraParams = (byte[]) row["ExtraParams"];
  1650. if (!(row["Media"] is System.DBNull))
  1651. s.Media = PrimitiveBaseShape.MediaList.FromXml((string)row["Media"]);
  1652. return s;
  1653. }
  1654. /// <summary>
  1655. ///
  1656. /// </summary>
  1657. /// <param name="row"></param>
  1658. /// <param name="prim"></param>
  1659. private static void fillShapeRow(DataRow row, SceneObjectPart prim)
  1660. {
  1661. PrimitiveBaseShape s = prim.Shape;
  1662. row["UUID"] = prim.UUID.ToString();
  1663. // shape is an enum
  1664. row["Shape"] = 0;
  1665. // vectors
  1666. row["ScaleX"] = s.Scale.X;
  1667. row["ScaleY"] = s.Scale.Y;
  1668. row["ScaleZ"] = s.Scale.Z;
  1669. // paths
  1670. row["PCode"] = s.PCode;
  1671. row["PathBegin"] = s.PathBegin;
  1672. row["PathEnd"] = s.PathEnd;
  1673. row["PathScaleX"] = s.PathScaleX;
  1674. row["PathScaleY"] = s.PathScaleY;
  1675. row["PathShearX"] = s.PathShearX;
  1676. row["PathShearY"] = s.PathShearY;
  1677. row["PathSkew"] = s.PathSkew;
  1678. row["PathCurve"] = s.PathCurve;
  1679. row["PathRadiusOffset"] = s.PathRadiusOffset;
  1680. row["PathRevolutions"] = s.PathRevolutions;
  1681. row["PathTaperX"] = s.PathTaperX;
  1682. row["PathTaperY"] = s.PathTaperY;
  1683. row["PathTwist"] = s.PathTwist;
  1684. row["PathTwistBegin"] = s.PathTwistBegin;
  1685. // profile
  1686. row["ProfileBegin"] = s.ProfileBegin;
  1687. row["ProfileEnd"] = s.ProfileEnd;
  1688. row["ProfileCurve"] = s.ProfileCurve;
  1689. row["ProfileHollow"] = s.ProfileHollow;
  1690. row["State"] = s.State;
  1691. row["Texture"] = s.TextureEntry;
  1692. row["ExtraParams"] = s.ExtraParams;
  1693. if (s.Media != null)
  1694. row["Media"] = s.Media.ToXml();
  1695. }
  1696. /// <summary>
  1697. /// Persistently store a prim.
  1698. /// </summary>
  1699. /// <param name="prim"></param>
  1700. /// <param name="sceneGroupID"></param>
  1701. /// <param name="regionUUID"></param>
  1702. private void addPrim(SceneObjectPart prim, UUID sceneGroupID, UUID regionUUID)
  1703. {
  1704. DataTable prims = ds.Tables["prims"];
  1705. DataTable shapes = ds.Tables["primshapes"];
  1706. DataRow primRow = prims.Rows.Find(prim.UUID.ToString());
  1707. if (primRow == null)
  1708. {
  1709. primRow = prims.NewRow();
  1710. fillPrimRow(primRow, prim, sceneGroupID, regionUUID);
  1711. prims.Rows.Add(primRow);
  1712. }
  1713. else
  1714. {
  1715. fillPrimRow(primRow, prim, sceneGroupID, regionUUID);
  1716. }
  1717. DataRow shapeRow = shapes.Rows.Find(prim.UUID.ToString());
  1718. if (shapeRow == null)
  1719. {
  1720. shapeRow = shapes.NewRow();
  1721. fillShapeRow(shapeRow, prim);
  1722. shapes.Rows.Add(shapeRow);
  1723. }
  1724. else
  1725. {
  1726. fillShapeRow(shapeRow, prim);
  1727. }
  1728. }
  1729. /// <summary>
  1730. /// </summary>
  1731. /// <param name="primID"></param>
  1732. /// <param name="items"></param>
  1733. public void StorePrimInventory(UUID primID, ICollection<TaskInventoryItem> items)
  1734. {
  1735. // m_log.DebugFormat("[SQLITE REGION DB]: Entered StorePrimInventory with prim ID {0}", primID);
  1736. DataTable dbItems = ds.Tables["primitems"];
  1737. // For now, we're just going to crudely remove all the previous inventory items
  1738. // no matter whether they have changed or not, and replace them with the current set.
  1739. lock (ds)
  1740. {
  1741. RemoveItems(primID);
  1742. // repalce with current inventory details
  1743. foreach (TaskInventoryItem newItem in items)
  1744. {
  1745. // m_log.InfoFormat(
  1746. // "[DATASTORE]: ",
  1747. // "Adding item {0}, {1} to prim ID {2}",
  1748. // newItem.Name, newItem.ItemID, newItem.ParentPartID);
  1749. DataRow newItemRow = dbItems.NewRow();
  1750. fillItemRow(newItemRow, newItem);
  1751. dbItems.Rows.Add(newItemRow);
  1752. }
  1753. }
  1754. Commit();
  1755. }
  1756. /***********************************************************************
  1757. *
  1758. * SQL Statement Creation Functions
  1759. *
  1760. * These functions create SQL statements for update, insert, and create.
  1761. * They can probably be factored later to have a db independant
  1762. * portion and a db specific portion
  1763. *
  1764. **********************************************************************/
  1765. /// <summary>
  1766. /// Create an insert command
  1767. /// </summary>
  1768. /// <param name="table">table name</param>
  1769. /// <param name="dt">data table</param>
  1770. /// <returns>the created command</returns>
  1771. /// <remarks>
  1772. /// This is subtle enough to deserve some commentary.
  1773. /// Instead of doing *lots* and *lots of hardcoded strings
  1774. /// for database definitions we'll use the fact that
  1775. /// realistically all insert statements look like "insert
  1776. /// into A(b, c) values(:b, :c) on the parameterized query
  1777. /// front. If we just have a list of b, c, etc... we can
  1778. /// generate these strings instead of typing them out.
  1779. /// </remarks>
  1780. private static SqliteCommand createInsertCommand(string table, DataTable dt)
  1781. {
  1782. string[] cols = new string[dt.Columns.Count];
  1783. for (int i = 0; i < dt.Columns.Count; i++)
  1784. {
  1785. DataColumn col = dt.Columns[i];
  1786. cols[i] = col.ColumnName;
  1787. }
  1788. string sql = "insert into " + table + "(";
  1789. sql += String.Join(", ", cols);
  1790. // important, the first ':' needs to be here, the rest get added in the join
  1791. sql += ") values (:";
  1792. sql += String.Join(", :", cols);
  1793. sql += ")";
  1794. //m_log.DebugFormat("[SQLITE]: Created insert command {0}", sql);
  1795. SqliteCommand cmd = new SqliteCommand(sql);
  1796. // this provides the binding for all our parameters, so
  1797. // much less code than it used to be
  1798. foreach (DataColumn col in dt.Columns)
  1799. {
  1800. cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType));
  1801. }
  1802. return cmd;
  1803. }
  1804. /// <summary>
  1805. /// create an update command
  1806. /// </summary>
  1807. /// <param name="table">table name</param>
  1808. /// <param name="pk"></param>
  1809. /// <param name="dt"></param>
  1810. /// <returns>the created command</returns>
  1811. private static SqliteCommand createUpdateCommand(string table, string pk, DataTable dt)
  1812. {
  1813. string sql = "update " + table + " set ";
  1814. string subsql = String.Empty;
  1815. foreach (DataColumn col in dt.Columns)
  1816. {
  1817. if (subsql.Length > 0)
  1818. {
  1819. // a map function would rock so much here
  1820. subsql += ", ";
  1821. }
  1822. subsql += col.ColumnName + "= :" + col.ColumnName;
  1823. }
  1824. sql += subsql;
  1825. sql += " where " + pk;
  1826. SqliteCommand cmd = new SqliteCommand(sql);
  1827. // this provides the binding for all our parameters, so
  1828. // much less code than it used to be
  1829. foreach (DataColumn col in dt.Columns)
  1830. {
  1831. cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType));
  1832. }
  1833. return cmd;
  1834. }
  1835. /// <summary>
  1836. /// create an update command
  1837. /// </summary>
  1838. /// <param name="table">table name</param>
  1839. /// <param name="pk"></param>
  1840. /// <param name="dt"></param>
  1841. /// <returns>the created command</returns>
  1842. private static SqliteCommand createUpdateCommand(string table, string pk1, string pk2, DataTable dt)
  1843. {
  1844. string sql = "update " + table + " set ";
  1845. string subsql = String.Empty;
  1846. foreach (DataColumn col in dt.Columns)
  1847. {
  1848. if (subsql.Length > 0)
  1849. {
  1850. // a map function would rock so much here
  1851. subsql += ", ";
  1852. }
  1853. subsql += col.ColumnName + "= :" + col.ColumnName;
  1854. }
  1855. sql += subsql;
  1856. sql += " where " + pk1 + " and " + pk2;
  1857. SqliteCommand cmd = new SqliteCommand(sql);
  1858. // this provides the binding for all our parameters, so
  1859. // much less code than it used to be
  1860. foreach (DataColumn col in dt.Columns)
  1861. {
  1862. cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType));
  1863. }
  1864. return cmd;
  1865. }
  1866. /// <summary>
  1867. ///
  1868. /// </summary>
  1869. /// <param name="dt">Data Table</param>
  1870. /// <returns></returns>
  1871. // private static string defineTable(DataTable dt)
  1872. // {
  1873. // string sql = "create table " + dt.TableName + "(";
  1874. // string subsql = String.Empty;
  1875. // foreach (DataColumn col in dt.Columns)
  1876. // {
  1877. // if (subsql.Length > 0)
  1878. // {
  1879. // // a map function would rock so much here
  1880. // subsql += ",\n";
  1881. // }
  1882. // subsql += col.ColumnName + " " + sqliteType(col.DataType);
  1883. // if (dt.PrimaryKey.Length > 0 && col == dt.PrimaryKey[0])
  1884. // {
  1885. // subsql += " primary key";
  1886. // }
  1887. // }
  1888. // sql += subsql;
  1889. // sql += ")";
  1890. // return sql;
  1891. // }
  1892. /***********************************************************************
  1893. *
  1894. * Database Binding functions
  1895. *
  1896. * These will be db specific due to typing, and minor differences
  1897. * in databases.
  1898. *
  1899. **********************************************************************/
  1900. ///<summary>
  1901. /// This is a convenience function that collapses 5 repetitive
  1902. /// lines for defining SqliteParameters to 2 parameters:
  1903. /// column name and database type.
  1904. ///
  1905. /// It assumes certain conventions like :param as the param
  1906. /// name to replace in parametrized queries, and that source
  1907. /// version is always current version, both of which are fine
  1908. /// for us.
  1909. ///</summary>
  1910. ///<returns>a built sqlite parameter</returns>
  1911. private static SqliteParameter createSqliteParameter(string name, Type type)
  1912. {
  1913. SqliteParameter param = new SqliteParameter();
  1914. param.ParameterName = ":" + name;
  1915. param.DbType = dbtypeFromType(type);
  1916. param.SourceColumn = name;
  1917. param.SourceVersion = DataRowVersion.Current;
  1918. return param;
  1919. }
  1920. /// <summary>
  1921. ///
  1922. /// </summary>
  1923. /// <param name="da"></param>
  1924. /// <param name="conn"></param>
  1925. private void setupPrimCommands(SqliteDataAdapter da, SqliteConnection conn)
  1926. {
  1927. da.InsertCommand = createInsertCommand("prims", ds.Tables["prims"]);
  1928. da.InsertCommand.Connection = conn;
  1929. da.UpdateCommand = createUpdateCommand("prims", "UUID=:UUID", ds.Tables["prims"]);
  1930. da.UpdateCommand.Connection = conn;
  1931. SqliteCommand delete = new SqliteCommand("delete from prims where UUID = :UUID");
  1932. delete.Parameters.Add(createSqliteParameter("UUID", typeof (String)));
  1933. delete.Connection = conn;
  1934. da.DeleteCommand = delete;
  1935. }
  1936. /// <summary>
  1937. ///
  1938. /// </summary>
  1939. /// <param name="da"></param>
  1940. /// <param name="conn"></param>
  1941. private void setupItemsCommands(SqliteDataAdapter da, SqliteConnection conn)
  1942. {
  1943. da.InsertCommand = createInsertCommand("primitems", ds.Tables["primitems"]);
  1944. da.InsertCommand.Connection = conn;
  1945. da.UpdateCommand = createUpdateCommand("primitems", "itemID = :itemID", ds.Tables["primitems"]);
  1946. da.UpdateCommand.Connection = conn;
  1947. SqliteCommand delete = new SqliteCommand("delete from primitems where itemID = :itemID");
  1948. delete.Parameters.Add(createSqliteParameter("itemID", typeof (String)));
  1949. delete.Connection = conn;
  1950. da.DeleteCommand = delete;
  1951. }
  1952. /// <summary>
  1953. ///
  1954. /// </summary>
  1955. /// <param name="da"></param>
  1956. /// <param name="conn"></param>
  1957. private void setupTerrainCommands(SqliteDataAdapter da, SqliteConnection conn)
  1958. {
  1959. da.InsertCommand = createInsertCommand("terrain", ds.Tables["terrain"]);
  1960. da.InsertCommand.Connection = conn;
  1961. }
  1962. /// <summary>
  1963. ///
  1964. /// </summary>
  1965. /// <param name="da"></param>
  1966. /// <param name="conn"></param>
  1967. private void setupLandCommands(SqliteDataAdapter da, SqliteConnection conn)
  1968. {
  1969. da.InsertCommand = createInsertCommand("land", ds.Tables["land"]);
  1970. da.InsertCommand.Connection = conn;
  1971. da.UpdateCommand = createUpdateCommand("land", "UUID=:UUID", ds.Tables["land"]);
  1972. da.UpdateCommand.Connection = conn;
  1973. SqliteCommand delete = new SqliteCommand("delete from land where UUID=:UUID");
  1974. delete.Parameters.Add(createSqliteParameter("UUID", typeof(String)));
  1975. da.DeleteCommand = delete;
  1976. da.DeleteCommand.Connection = conn;
  1977. }
  1978. /// <summary>
  1979. ///
  1980. /// </summary>
  1981. /// <param name="da"></param>
  1982. /// <param name="conn"></param>
  1983. private void setupLandAccessCommands(SqliteDataAdapter da, SqliteConnection conn)
  1984. {
  1985. da.InsertCommand = createInsertCommand("landaccesslist", ds.Tables["landaccesslist"]);
  1986. da.InsertCommand.Connection = conn;
  1987. da.UpdateCommand = createUpdateCommand("landaccesslist", "LandUUID=:landUUID", "AccessUUID=:AccessUUID", ds.Tables["landaccesslist"]);
  1988. da.UpdateCommand.Connection = conn;
  1989. SqliteCommand delete = new SqliteCommand("delete from landaccesslist where LandUUID= :LandUUID and AccessUUID= :AccessUUID");
  1990. delete.Parameters.Add(createSqliteParameter("LandUUID", typeof(String)));
  1991. delete.Parameters.Add(createSqliteParameter("AccessUUID", typeof(String)));
  1992. da.DeleteCommand = delete;
  1993. da.DeleteCommand.Connection = conn;
  1994. }
  1995. private void setupRegionSettingsCommands(SqliteDataAdapter da, SqliteConnection conn)
  1996. {
  1997. da.InsertCommand = createInsertCommand("regionsettings", ds.Tables["regionsettings"]);
  1998. da.InsertCommand.Connection = conn;
  1999. da.UpdateCommand = createUpdateCommand("regionsettings", "regionUUID=:regionUUID", ds.Tables["regionsettings"]);
  2000. da.UpdateCommand.Connection = conn;
  2001. }
  2002. /// <summary>
  2003. ///
  2004. /// </summary>
  2005. /// <param name="da"></param>
  2006. /// <param name="conn"></param>
  2007. private void setupShapeCommands(SqliteDataAdapter da, SqliteConnection conn)
  2008. {
  2009. da.InsertCommand = createInsertCommand("primshapes", ds.Tables["primshapes"]);
  2010. da.InsertCommand.Connection = conn;
  2011. da.UpdateCommand = createUpdateCommand("primshapes", "UUID=:UUID", ds.Tables["primshapes"]);
  2012. da.UpdateCommand.Connection = conn;
  2013. SqliteCommand delete = new SqliteCommand("delete from primshapes where UUID = :UUID");
  2014. delete.Parameters.Add(createSqliteParameter("UUID", typeof (String)));
  2015. delete.Connection = conn;
  2016. da.DeleteCommand = delete;
  2017. }
  2018. /***********************************************************************
  2019. *
  2020. * Type conversion functions
  2021. *
  2022. **********************************************************************/
  2023. /// <summary>
  2024. /// Type conversion function
  2025. /// </summary>
  2026. /// <param name="type"></param>
  2027. /// <returns></returns>
  2028. private static DbType dbtypeFromType(Type type)
  2029. {
  2030. if (type == typeof (String))
  2031. {
  2032. return DbType.String;
  2033. }
  2034. else if (type == typeof (Int32))
  2035. {
  2036. return DbType.Int32;
  2037. }
  2038. else if (type == typeof (Double))
  2039. {
  2040. return DbType.Double;
  2041. }
  2042. else if (type == typeof (Byte))
  2043. {
  2044. return DbType.Byte;
  2045. }
  2046. else if (type == typeof (Double))
  2047. {
  2048. return DbType.Double;
  2049. }
  2050. else if (type == typeof (Byte[]))
  2051. {
  2052. return DbType.Binary;
  2053. }
  2054. else
  2055. {
  2056. return DbType.String;
  2057. }
  2058. }
  2059. static void PrintDataSet(DataSet ds)
  2060. {
  2061. // Print out any name and extended properties.
  2062. Console.WriteLine("DataSet is named: {0}", ds.DataSetName);
  2063. foreach (System.Collections.DictionaryEntry de in ds.ExtendedProperties)
  2064. {
  2065. Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
  2066. }
  2067. Console.WriteLine();
  2068. foreach (DataTable dt in ds.Tables)
  2069. {
  2070. Console.WriteLine("=> {0} Table:", dt.TableName);
  2071. // Print out the column names.
  2072. for (int curCol = 0; curCol < dt.Columns.Count; curCol++)
  2073. {
  2074. Console.Write(dt.Columns[curCol].ColumnName + "\t");
  2075. }
  2076. Console.WriteLine("\n----------------------------------");
  2077. // Print the DataTable.
  2078. for (int curRow = 0; curRow < dt.Rows.Count; curRow++)
  2079. {
  2080. for (int curCol = 0; curCol < dt.Columns.Count; curCol++)
  2081. {
  2082. Console.Write(dt.Rows[curRow][curCol].ToString() + "\t");
  2083. }
  2084. Console.WriteLine();
  2085. }
  2086. }
  2087. }
  2088. }
  2089. }