SQLiteRegionData.cs 99 KB

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