SQLiteRegionData.cs 73 KB

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