SQLiteSimulationData.cs 100 KB

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