MSSQLDataStore.cs 74 KB

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