SQLiteRegionData.cs 81 KB

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