SQLiteRegionData.cs 73 KB

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