SQLiteRegionData.cs 100 KB

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