SQLiteRegionData.cs 86 KB

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