MySQLDataStore.cs 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSim Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Data;
  30. using System.IO;
  31. using System.Reflection;
  32. using System.Threading;
  33. using libsecondlife;
  34. using log4net;
  35. using MySql.Data.MySqlClient;
  36. using OpenSim.Framework;
  37. using OpenSim.Region.Environment.Interfaces;
  38. using OpenSim.Region.Environment.Scenes;
  39. namespace OpenSim.Data.MySQL
  40. {
  41. /// <summary>
  42. /// A MySQL Interface for the Region Server
  43. /// </summary>
  44. public class MySQLDataStore : IRegionDataStore
  45. {
  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 * from terrain limit 1";
  51. private const string m_landSelect = "select * from land";
  52. private const string m_landAccessListSelect = "select * from landaccesslist";
  53. private const string m_regionSettingsSelect = "select * from regionsettings";
  54. private const string m_waitTimeoutSelect = "select @@wait_timeout";
  55. private MySqlConnection m_connection;
  56. private string m_connectionString;
  57. /// <summary>
  58. /// Wait timeout for our connection in ticks.
  59. /// </summary>
  60. private long m_waitTimeout;
  61. /// <summary>
  62. /// Make our storage of the timeout this amount smaller than it actually is, to give us a margin on long
  63. /// running database operations.
  64. /// </summary>
  65. private long m_waitTimeoutLeeway = 60 * TimeSpan.TicksPerSecond;
  66. /// <summary>
  67. /// Holds the last tick time that the connection was used.
  68. /// </summary>
  69. private long m_lastConnectionUse;
  70. private DataSet m_dataSet;
  71. private MySqlDataAdapter m_primDataAdapter;
  72. private MySqlDataAdapter m_shapeDataAdapter;
  73. private MySqlDataAdapter m_itemsDataAdapter;
  74. private MySqlDataAdapter m_terrainDataAdapter;
  75. private MySqlDataAdapter m_landDataAdapter;
  76. private MySqlDataAdapter m_landAccessListDataAdapter;
  77. private MySqlDataAdapter m_regionSettingsDataAdapter;
  78. private DataTable m_primTable;
  79. private DataTable m_shapeTable;
  80. private DataTable m_itemsTable;
  81. private DataTable m_terrainTable;
  82. private DataTable m_landTable;
  83. private DataTable m_landAccessListTable;
  84. private DataTable m_regionSettingsTable;
  85. /// <value>Temporary attribute while this is experimental</value>
  86. private bool persistPrimInventories;
  87. /***********************************************************************
  88. *
  89. * Public Interface Functions
  90. *
  91. **********************************************************************/
  92. /// <summary>
  93. /// see IRegionDataStore
  94. /// </summary>
  95. /// <param name="connectionstring"></param>
  96. /// <param name="persistPrimInventories"></param>
  97. public void Initialise(string connectionString, bool persistPrimInventories)
  98. {
  99. m_connectionString = connectionString;
  100. m_dataSet = new DataSet();
  101. this.persistPrimInventories = persistPrimInventories;
  102. int passPosition = 0;
  103. int passEndPosition = 0;
  104. string displayConnectionString = null;
  105. try
  106. { // hide the password in the connection string
  107. passPosition = m_connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase);
  108. passPosition = m_connectionString.IndexOf("=", passPosition);
  109. if (passPosition < m_connectionString.Length)
  110. passPosition += 1;
  111. passEndPosition = m_connectionString.IndexOf(";", passPosition);
  112. displayConnectionString = m_connectionString.Substring(0, passPosition);
  113. displayConnectionString += "***";
  114. displayConnectionString += m_connectionString.Substring(passEndPosition, m_connectionString.Length - passEndPosition);
  115. }
  116. catch (Exception e )
  117. {
  118. m_log.Debug("Exception: password not found in connection string\n" + e.ToString());
  119. }
  120. m_log.Info("[REGION DB]: MySql - connecting: " + displayConnectionString);
  121. m_connection = new MySqlConnection(m_connectionString);
  122. m_connection.Open();
  123. GetWaitTimeout();
  124. // This actually does the roll forward assembly stuff
  125. Assembly assem = GetType().Assembly;
  126. Migration m = new Migration(m_connection, assem, "RegionStore");
  127. // TODO: After rev 6000, remove this. People should have
  128. // been rolled onto the new migration code by then.
  129. TestTables(m_connection, m);
  130. m.Update();
  131. MySqlCommand primSelectCmd = new MySqlCommand(m_primSelect, m_connection);
  132. m_primDataAdapter = new MySqlDataAdapter(primSelectCmd);
  133. MySqlCommand shapeSelectCmd = new MySqlCommand(m_shapeSelect, m_connection);
  134. m_shapeDataAdapter = new MySqlDataAdapter(shapeSelectCmd);
  135. MySqlCommand itemsSelectCmd = new MySqlCommand(m_itemsSelect, m_connection);
  136. m_itemsDataAdapter = new MySqlDataAdapter(itemsSelectCmd);
  137. MySqlCommand terrainSelectCmd = new MySqlCommand(m_terrainSelect, m_connection);
  138. m_terrainDataAdapter = new MySqlDataAdapter(terrainSelectCmd);
  139. MySqlCommand landSelectCmd = new MySqlCommand(m_landSelect, m_connection);
  140. m_landDataAdapter = new MySqlDataAdapter(landSelectCmd);
  141. MySqlCommand landAccessListSelectCmd = new MySqlCommand(m_landAccessListSelect, m_connection);
  142. m_landAccessListDataAdapter = new MySqlDataAdapter(landAccessListSelectCmd);
  143. MySqlCommand regionSettingsSelectCmd = new MySqlCommand(m_regionSettingsSelect, m_connection);
  144. m_regionSettingsDataAdapter = new MySqlDataAdapter(regionSettingsSelectCmd);
  145. lock (m_dataSet)
  146. {
  147. m_primTable = createPrimTable();
  148. m_dataSet.Tables.Add(m_primTable);
  149. SetupPrimCommands(m_primDataAdapter, m_connection);
  150. m_primDataAdapter.Fill(m_primTable);
  151. m_shapeTable = createShapeTable();
  152. m_dataSet.Tables.Add(m_shapeTable);
  153. SetupShapeCommands(m_shapeDataAdapter, m_connection);
  154. m_shapeDataAdapter.Fill(m_shapeTable);
  155. if (persistPrimInventories)
  156. {
  157. m_itemsTable = createItemsTable();
  158. m_dataSet.Tables.Add(m_itemsTable);
  159. SetupItemsCommands(m_itemsDataAdapter, m_connection);
  160. m_itemsDataAdapter.Fill(m_itemsTable);
  161. }
  162. m_terrainTable = createTerrainTable();
  163. m_dataSet.Tables.Add(m_terrainTable);
  164. SetupTerrainCommands(m_terrainDataAdapter, m_connection);
  165. m_terrainDataAdapter.Fill(m_terrainTable);
  166. m_landTable = createLandTable();
  167. m_dataSet.Tables.Add(m_landTable);
  168. setupLandCommands(m_landDataAdapter, m_connection);
  169. m_landDataAdapter.Fill(m_landTable);
  170. m_landAccessListTable = createLandAccessListTable();
  171. m_dataSet.Tables.Add(m_landAccessListTable);
  172. setupLandAccessCommands(m_landAccessListDataAdapter, m_connection);
  173. m_landAccessListDataAdapter.Fill(m_landAccessListTable);
  174. m_regionSettingsTable = createRegionSettingsTable();
  175. m_dataSet.Tables.Add(m_regionSettingsTable);
  176. SetupRegionSettingsCommands(m_regionSettingsDataAdapter, m_connection);
  177. m_regionSettingsDataAdapter.Fill(m_regionSettingsTable);
  178. }
  179. }
  180. /// <summary>
  181. /// Get the wait_timeout value for our connection
  182. /// </summary>
  183. protected void GetWaitTimeout()
  184. {
  185. MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, m_connection);
  186. using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
  187. {
  188. if (dbReader.Read())
  189. {
  190. m_waitTimeout
  191. = Convert.ToInt32(dbReader["@@wait_timeout"]) * TimeSpan.TicksPerSecond + m_waitTimeoutLeeway;
  192. }
  193. dbReader.Close();
  194. cmd.Dispose();
  195. }
  196. m_lastConnectionUse = System.DateTime.Now.Ticks;
  197. m_log.DebugFormat(
  198. "[REGION DB]: Connection wait timeout {0} seconds", m_waitTimeout / TimeSpan.TicksPerSecond);
  199. }
  200. /// <summary>
  201. /// Should be called before any db operation. This checks to see if the connection has not timed out
  202. /// </summary>
  203. protected void CheckConnection()
  204. {
  205. //m_log.Debug("[REGION DB]: Checking connection");
  206. long timeNow = System.DateTime.Now.Ticks;
  207. if (timeNow - m_lastConnectionUse > m_waitTimeout || m_connection.State != ConnectionState.Open)
  208. {
  209. m_log.DebugFormat("[REGION DB]: Database connection has gone away - reconnecting");
  210. lock (m_connection)
  211. {
  212. m_connection.Close();
  213. m_connection = new MySqlConnection(m_connectionString);
  214. m_connection.Open();
  215. }
  216. }
  217. // Strictly, we should set this after the actual db operation. But it's more convenient to set here rather
  218. // than require the code to call another method - the timeout leeway should be large enough to cover the
  219. // inaccuracy.
  220. m_lastConnectionUse = timeNow;
  221. }
  222. /// <summary>
  223. /// Given a list of tables, return the version of the tables, as seen in the database
  224. /// </summary>
  225. /// <param name="tableList">The list of table</param>
  226. /// <param name="dbcon">The database connection handler</param>
  227. public void GetTableVersion(Dictionary<string, string> tableList, MySqlConnection dbcon)
  228. {
  229. lock (dbcon)
  230. {
  231. MySqlCommand tablesCmd =
  232. new MySqlCommand(
  233. "SELECT TABLE_NAME, TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=?dbname",
  234. dbcon);
  235. tablesCmd.Parameters.AddWithValue("?dbname", dbcon.Database);
  236. CheckConnection();
  237. using (MySqlDataReader tables = tablesCmd.ExecuteReader())
  238. {
  239. while (tables.Read())
  240. {
  241. try
  242. {
  243. string tableName = (string)tables["TABLE_NAME"];
  244. string comment = (string)tables["TABLE_COMMENT"];
  245. if (tableList.ContainsKey(tableName))
  246. {
  247. tableList[tableName] = comment;
  248. }
  249. }
  250. catch (Exception e)
  251. {
  252. m_log.Error(e.ToString());
  253. }
  254. }
  255. tables.Close();
  256. }
  257. }
  258. }
  259. // private void TestTablesVersionable(MySqlConnection dbconn)
  260. // {
  261. // Dictionary<string, string> tableList = new Dictionary<string, string>();
  262. // tableList["land"] = null;
  263. // dbconn.Open();
  264. // GetTableVersion(tableList,dbconn);
  265. // UpgradeLandTable(tableList["land"], dbconn);
  266. // //database.Close();
  267. // }
  268. /// <summary>
  269. /// Execute a SQL statement stored in a resource, as a string
  270. /// </summary>
  271. /// <param name="name">the ressource name</param>
  272. /// <param name="dbcon">The database connection handler</param>
  273. public void ExecuteResourceSql(string name, MySqlConnection dbcon)
  274. {
  275. MySqlCommand cmd = new MySqlCommand(getResourceString(name), dbcon);
  276. cmd.ExecuteNonQuery();
  277. }
  278. /// <summary>
  279. /// Extract a named string resource from the embedded resources
  280. /// </summary>
  281. /// <param name="name">name of embedded resource</param>
  282. /// <returns>string contained within the embedded resource</returns>
  283. private string getResourceString(string name)
  284. {
  285. Assembly assem = GetType().Assembly;
  286. string[] names = assem.GetManifestResourceNames();
  287. foreach (string s in names)
  288. {
  289. if (s.EndsWith(name))
  290. {
  291. using (Stream resource = assem.GetManifestResourceStream(s))
  292. {
  293. using (StreamReader resourceReader = new StreamReader(resource))
  294. {
  295. string resourceString = resourceReader.ReadToEnd();
  296. return resourceString;
  297. }
  298. }
  299. }
  300. }
  301. throw new Exception(string.Format("Resource '{0}' was not found", name));
  302. }
  303. /// <summary>
  304. /// <list type="bullet">
  305. /// <item>Execute CreateLandTable.sql if oldVersion == null</item>
  306. /// <item>Execute UpgradeLandTable.sqm if oldVersion contain "Rev."</item>
  307. /// </list>
  308. /// </summary>
  309. /// <param name="oldVersion"></param>
  310. /// <param name="dbconn">The database connection handler</param>
  311. // private void UpgradeLandTable(string oldVersion, MySqlConnection dbconn)
  312. // {
  313. // // null as the version, indicates that the table didn't exist
  314. // if (oldVersion == null)
  315. // {
  316. // ExecuteResourceSql("CreateLandTable.sql",dbconn);
  317. // oldVersion = "Rev. 2; InnoDB free: 0 kB";
  318. // }
  319. // if (!oldVersion.Contains("Rev."))
  320. // {
  321. // ExecuteResourceSql("UpgradeLandTableToVersion2.sql", dbconn);
  322. // }
  323. // }
  324. /// <summary>
  325. /// Adds an object into region storage
  326. /// </summary>
  327. /// <param name="obj">The object</param>
  328. /// <param name="regionUUID">The region UUID</param>
  329. public void StoreObject(SceneObjectGroup obj, LLUUID regionUUID)
  330. {
  331. lock (m_dataSet)
  332. {
  333. foreach (SceneObjectPart prim in obj.Children.Values)
  334. {
  335. if ((prim.GetEffectiveObjectFlags() & (uint)LLObject.ObjectFlags.Physics) == 0
  336. && (prim.GetEffectiveObjectFlags() & (uint)LLObject.ObjectFlags.Temporary) == 0
  337. && (prim.GetEffectiveObjectFlags() & (uint)LLObject.ObjectFlags.TemporaryOnRez) == 0)
  338. {
  339. //m_log.Info("[REGION DB]: Adding obj: " + obj.UUID + " to region: " + regionUUID);
  340. addPrim(prim, obj.UUID, regionUUID);
  341. }
  342. else
  343. {
  344. // m_log.Info("[DATASTORE]: Ignoring Physical obj: " + obj.UUID + " in region: " + regionUUID);
  345. }
  346. }
  347. Commit();
  348. }
  349. }
  350. /// <summary>
  351. /// removes an object from region storage
  352. /// </summary>
  353. /// <param name="obj">The object</param>
  354. /// <param name="regionUUID">The Region UUID</param>
  355. public void RemoveObject(LLUUID obj, LLUUID regionUUID)
  356. {
  357. m_log.InfoFormat("[REGION DB]: Removing obj: {0} from region: {1}", obj.UUID, regionUUID);
  358. DataTable prims = m_primTable;
  359. DataTable shapes = m_shapeTable;
  360. string selectExp = "SceneGroupID = '" + Util.ToRawUuidString(obj) + "'";
  361. lock (m_dataSet)
  362. {
  363. DataRow[] primRows = prims.Select(selectExp);
  364. foreach (DataRow row in primRows)
  365. {
  366. // Remove shapes row
  367. LLUUID uuid = new LLUUID((string) row["UUID"]);
  368. DataRow shapeRow = shapes.Rows.Find(Util.ToRawUuidString(uuid));
  369. if (shapeRow != null)
  370. {
  371. shapeRow.Delete();
  372. }
  373. if (persistPrimInventories)
  374. {
  375. RemoveItems(uuid);
  376. }
  377. // Remove prim row
  378. row.Delete();
  379. }
  380. Commit();
  381. }
  382. }
  383. /// <summary>
  384. /// Remove all persisted items of the given prim.
  385. /// The caller must acquire the necessrary synchronization locks and commit or rollback changes.
  386. /// </summary>
  387. /// <param name="uuid">the Item UUID</param>
  388. private void RemoveItems(LLUUID uuid)
  389. {
  390. String sql = String.Format("primID = '{0}'", uuid);
  391. DataRow[] itemRows = m_itemsTable.Select(sql);
  392. foreach (DataRow itemRow in itemRows)
  393. {
  394. itemRow.Delete();
  395. }
  396. }
  397. /// <summary>
  398. /// Load persisted objects from region storage.
  399. /// </summary>
  400. /// <param name="regionUUID">the Region UUID</param>
  401. /// <returns>List of loaded groups</returns>
  402. public List<SceneObjectGroup> LoadObjects(LLUUID regionUUID)
  403. {
  404. Dictionary<LLUUID, SceneObjectGroup> createdObjects = new Dictionary<LLUUID, SceneObjectGroup>();
  405. List<SceneObjectGroup> retvals = new List<SceneObjectGroup>();
  406. DataTable prims = m_primTable;
  407. DataTable shapes = m_shapeTable;
  408. string byRegion = "RegionUUID = '" + Util.ToRawUuidString(regionUUID) + "'";
  409. string orderByParent = "ParentID ASC";
  410. lock (m_dataSet)
  411. {
  412. CheckConnection();
  413. DataRow[] primsForRegion = prims.Select(byRegion, orderByParent);
  414. m_log.Info("[REGION DB]: " +
  415. "Loaded " + primsForRegion.Length + " prims for region: " + regionUUID);
  416. foreach (DataRow primRow in primsForRegion)
  417. {
  418. try
  419. {
  420. string uuid = (string) primRow["UUID"];
  421. string objID = (string) primRow["SceneGroupID"];
  422. SceneObjectPart prim = buildPrim(primRow);
  423. if (uuid == objID) //is new SceneObjectGroup ?
  424. {
  425. SceneObjectGroup group = new SceneObjectGroup();
  426. DataRow shapeRow = shapes.Rows.Find(Util.ToRawUuidString(prim.UUID));
  427. if (shapeRow != null)
  428. {
  429. prim.Shape = buildShape(shapeRow);
  430. }
  431. else
  432. {
  433. m_log.Info(
  434. "No shape found for prim in storage, so setting default box shape");
  435. prim.Shape = PrimitiveBaseShape.Default;
  436. }
  437. group.AddPart(prim);
  438. group.RootPart = prim;
  439. createdObjects.Add(group.UUID, group);
  440. retvals.Add(group);
  441. }
  442. else
  443. {
  444. DataRow shapeRow = shapes.Rows.Find(Util.ToRawUuidString(prim.UUID));
  445. if (shapeRow != null)
  446. {
  447. prim.Shape = buildShape(shapeRow);
  448. }
  449. else
  450. {
  451. m_log.Info(
  452. "No shape found for prim in storage, so setting default box shape");
  453. prim.Shape = PrimitiveBaseShape.Default;
  454. }
  455. createdObjects[new LLUUID(objID)].AddPart(prim);
  456. }
  457. if (persistPrimInventories)
  458. {
  459. LoadItems(prim);
  460. }
  461. }
  462. catch (Exception e)
  463. {
  464. m_log.Error("[REGION DB]: Failed create prim object, exception and data follows");
  465. m_log.Info("[REGION DB]: " + e.ToString());
  466. foreach (DataColumn col in prims.Columns)
  467. {
  468. m_log.Info("[REGION DB]: Col: " + col.ColumnName + " => " + primRow[col]);
  469. }
  470. }
  471. }
  472. }
  473. return retvals;
  474. }
  475. /// <summary>
  476. /// Load in a prim's persisted inventory.
  477. /// </summary>
  478. /// <param name="prim">The prim</param>
  479. private void LoadItems(SceneObjectPart prim)
  480. {
  481. lock (m_dataSet)
  482. {
  483. CheckConnection();
  484. //m_log.InfoFormat("[DATASTORE]: Loading inventory for {0}, {1}", prim.Name, prim.UUID);
  485. DataTable dbItems = m_itemsTable;
  486. String sql = String.Format("primID = '{0}'", prim.UUID.ToString());
  487. DataRow[] dbItemRows = dbItems.Select(sql);
  488. IList<TaskInventoryItem> inventory = new List<TaskInventoryItem>();
  489. foreach (DataRow row in dbItemRows)
  490. {
  491. TaskInventoryItem item = buildItem(row);
  492. inventory.Add(item);
  493. //m_log.DebugFormat("[DATASTORE]: Restored item {0}, {1}", item.Name, item.ItemID);
  494. }
  495. prim.RestoreInventoryItems(inventory);
  496. // XXX A nasty little hack to recover the folder id for the prim (which is currently stored in
  497. // every item). This data should really be stored in the prim table itself.
  498. if (dbItemRows.Length > 0)
  499. {
  500. prim.FolderID = inventory[0].ParentID;
  501. }
  502. }
  503. }
  504. /// <summary>
  505. /// Store a terrain revision in region storage
  506. /// </summary>
  507. /// <param name="ter">HeightField data</param>
  508. /// <param name="regionID">region UUID</param>
  509. public void StoreTerrain(double[,] ter, LLUUID regionID)
  510. {
  511. int revision = 1;
  512. m_log.Info("[REGION DB]: Storing terrain revision r" + revision.ToString());
  513. lock (m_dataSet)
  514. {
  515. MySqlCommand delete = new MySqlCommand("delete from terrain where RegionUUID=?RegionUUID", m_connection);
  516. MySqlCommand cmd = new MySqlCommand("insert into terrain(RegionUUID, Revision, Heightfield)" +
  517. " values(?RegionUUID, ?Revision, ?Heightfield)", m_connection);
  518. using (cmd)
  519. {
  520. delete.Parameters.Add(new MySqlParameter("?RegionUUID", Util.ToRawUuidString(regionID)));
  521. CheckConnection();
  522. delete.ExecuteNonQuery();
  523. cmd.Parameters.Add(new MySqlParameter("?RegionUUID", Util.ToRawUuidString(regionID)));
  524. cmd.Parameters.Add(new MySqlParameter("?Revision", revision));
  525. cmd.Parameters.Add(new MySqlParameter("?Heightfield", serializeTerrain(ter)));
  526. cmd.ExecuteNonQuery();
  527. }
  528. }
  529. }
  530. /// <summary>
  531. /// Load the latest terrain revision from region storage
  532. /// </summary>
  533. /// <param name="regionID">the region UUID</param>
  534. /// <returns>Heightfield data</returns>
  535. public double[,] LoadTerrain(LLUUID regionID)
  536. {
  537. double[,] terret = new double[256,256];
  538. terret.Initialize();
  539. MySqlCommand cmd = new MySqlCommand(
  540. @"select RegionUUID, Revision, Heightfield from terrain
  541. where RegionUUID=?RegionUUID order by Revision desc limit 1"
  542. , m_connection);
  543. // MySqlParameter param = new MySqlParameter();
  544. cmd.Parameters.Add(new MySqlParameter("?RegionUUID", Util.ToRawUuidString(regionID)));
  545. if (m_connection.State != ConnectionState.Open)
  546. {
  547. m_connection.Open();
  548. }
  549. lock (m_dataSet)
  550. {
  551. CheckConnection();
  552. using (MySqlDataReader row = cmd.ExecuteReader())
  553. {
  554. int rev = 0;
  555. if (row.Read())
  556. {
  557. MemoryStream str = new MemoryStream((byte[]) row["Heightfield"]);
  558. BinaryReader br = new BinaryReader(str);
  559. for (int x = 0; x < 256; x++)
  560. {
  561. for (int y = 0; y < 256; y++)
  562. {
  563. terret[x, y] = br.ReadDouble();
  564. }
  565. }
  566. rev = (int) row["Revision"];
  567. }
  568. else
  569. {
  570. m_log.Info("[REGION DB]: No terrain found for region");
  571. return null;
  572. }
  573. m_log.Info("[REGION DB]: Loaded terrain revision r" + rev.ToString());
  574. }
  575. }
  576. return terret;
  577. }
  578. /// <summary>
  579. /// <list type="bullet">
  580. /// <item>delete from land where UUID=globalID</item>
  581. /// <item>delete from landaccesslist where LandUUID=globalID</item>
  582. /// </list>
  583. /// </summary>
  584. /// <param name="globalID"></param>
  585. public void RemoveLandObject(LLUUID globalID)
  586. {
  587. lock (m_dataSet)
  588. {
  589. CheckConnection();
  590. using (MySqlCommand cmd = new MySqlCommand("delete from land where UUID=?UUID", m_connection))
  591. {
  592. cmd.Parameters.Add(new MySqlParameter("?UUID", Util.ToRawUuidString(globalID)));
  593. cmd.ExecuteNonQuery();
  594. }
  595. using (
  596. MySqlCommand cmd = new MySqlCommand("delete from landaccesslist where LandUUID=?UUID", m_connection)
  597. )
  598. {
  599. cmd.Parameters.Add(new MySqlParameter("?UUID", Util.ToRawUuidString(globalID)));
  600. cmd.ExecuteNonQuery();
  601. }
  602. }
  603. }
  604. /// <summary>
  605. /// </summary>
  606. /// <param name="parcel"></param>
  607. public void StoreLandObject(ILandObject parcel)
  608. {
  609. lock (m_dataSet)
  610. {
  611. CheckConnection();
  612. DataTable land = m_landTable;
  613. DataTable landaccesslist = m_landAccessListTable;
  614. DataRow landRow = land.Rows.Find(Util.ToRawUuidString(parcel.landData.globalID));
  615. if (landRow == null)
  616. {
  617. landRow = land.NewRow();
  618. fillLandRow(landRow, parcel.landData, parcel.regionUUID);
  619. land.Rows.Add(landRow);
  620. }
  621. else
  622. {
  623. fillLandRow(landRow, parcel.landData, parcel.regionUUID);
  624. }
  625. using (
  626. MySqlCommand cmd =
  627. new MySqlCommand("delete from landaccesslist where LandUUID=?LandUUID", m_connection))
  628. {
  629. cmd.Parameters.Add(new MySqlParameter("?LandUUID", Util.ToRawUuidString(parcel.landData.globalID)));
  630. cmd.ExecuteNonQuery();
  631. }
  632. foreach (ParcelManager.ParcelAccessEntry entry in parcel.landData.parcelAccessList)
  633. {
  634. DataRow newAccessRow = landaccesslist.NewRow();
  635. fillLandAccessRow(newAccessRow, entry, parcel.landData.globalID);
  636. landaccesslist.Rows.Add(newAccessRow);
  637. }
  638. Commit();
  639. }
  640. }
  641. public RegionSettings LoadRegionSettings(LLUUID regionUUID)
  642. {
  643. lock (m_dataSet)
  644. {
  645. CheckConnection();
  646. DataTable regionsettings = m_regionSettingsTable;
  647. string searchExp = "regionUUID = '" + regionUUID.ToString() + "'";
  648. DataRow[] rawsettings = regionsettings.Select(searchExp);
  649. if (rawsettings.Length == 0)
  650. {
  651. RegionSettings rs = new RegionSettings();
  652. rs.RegionUUID = regionUUID;
  653. StoreRegionSettings(rs);
  654. return rs;
  655. }
  656. DataRow row = rawsettings[0];
  657. return buildRegionSettings(row);
  658. }
  659. }
  660. public void StoreRegionSettings(RegionSettings rs)
  661. {
  662. lock (m_dataSet)
  663. {
  664. CheckConnection();
  665. DataTable regionsettings = m_dataSet.Tables["regionsettings"];
  666. DataRow settingsRow = regionsettings.Rows.Find(rs.RegionUUID.ToString());
  667. if (settingsRow == null)
  668. {
  669. settingsRow = regionsettings.NewRow();
  670. fillRegionSettingsRow(settingsRow, rs);
  671. regionsettings.Rows.Add(settingsRow);
  672. }
  673. else
  674. {
  675. fillRegionSettingsRow(settingsRow, rs);
  676. }
  677. Commit();
  678. }
  679. }
  680. /// <summary>
  681. ///
  682. /// </summary>
  683. /// <param name="regionUUID"></param>
  684. /// <returns></returns>
  685. public List<LandData> LoadLandObjects(LLUUID regionUUID)
  686. {
  687. List<LandData> landDataForRegion = new List<LandData>();
  688. lock (m_dataSet)
  689. {
  690. CheckConnection();
  691. DataTable land = m_landTable;
  692. DataTable landaccesslist = m_landAccessListTable;
  693. string searchExp = "RegionUUID = '" + Util.ToRawUuidString(regionUUID) + "'";
  694. DataRow[] rawDataForRegion = land.Select(searchExp);
  695. foreach (DataRow rawDataLand in rawDataForRegion)
  696. {
  697. LandData newLand = buildLandData(rawDataLand);
  698. string accessListSearchExp = "LandUUID = '" + Util.ToRawUuidString(newLand.globalID) + "'";
  699. DataRow[] rawDataForLandAccessList = landaccesslist.Select(accessListSearchExp);
  700. foreach (DataRow rawDataLandAccess in rawDataForLandAccessList)
  701. {
  702. newLand.parcelAccessList.Add(buildLandAccessData(rawDataLandAccess));
  703. }
  704. landDataForRegion.Add(newLand);
  705. }
  706. }
  707. return landDataForRegion;
  708. }
  709. /// <summary>
  710. ///
  711. /// </summary>
  712. public void Commit()
  713. {
  714. lock (m_dataSet)
  715. {
  716. CheckConnection();
  717. // DisplayDataSet(m_dataSet, "Region DataSet");
  718. m_primDataAdapter.Update(m_primTable);
  719. m_shapeDataAdapter.Update(m_shapeTable);
  720. if (persistPrimInventories)
  721. {
  722. m_itemsDataAdapter.Update(m_itemsTable);
  723. }
  724. m_terrainDataAdapter.Update(m_terrainTable);
  725. m_landDataAdapter.Update(m_landTable);
  726. m_landAccessListDataAdapter.Update(m_landAccessListTable);
  727. m_regionSettingsDataAdapter.Update(m_regionSettingsTable);
  728. m_dataSet.AcceptChanges();
  729. }
  730. }
  731. /// <summary>
  732. /// See <see cref="Commit"/>
  733. /// </summary>
  734. public void Shutdown()
  735. {
  736. Commit();
  737. }
  738. /***********************************************************************
  739. *
  740. * Database Definition Functions
  741. *
  742. * This should be db agnostic as we define them in ADO.NET terms
  743. *
  744. **********************************************************************/
  745. /// <summary>
  746. ///
  747. /// </summary>
  748. /// <param name="dt"></param>
  749. /// <param name="name"></param>
  750. /// <param name="type"></param>
  751. /// <returns></returns>
  752. private static DataColumn createCol(DataTable dt, string name, Type type)
  753. {
  754. DataColumn col = new DataColumn(name, type);
  755. dt.Columns.Add(col);
  756. return col;
  757. }
  758. /// <summary>
  759. /// Create the "terrain" table
  760. /// </summary>
  761. /// <returns></returns>
  762. private static DataTable createTerrainTable()
  763. {
  764. DataTable terrain = new DataTable("terrain");
  765. createCol(terrain, "RegionUUID", typeof (String));
  766. createCol(terrain, "Revision", typeof (Int32));
  767. createCol(terrain, "Heightfield", typeof (Byte[]));
  768. return terrain;
  769. }
  770. /// <summary>
  771. /// Create the "regionsettings" table
  772. /// </summary>
  773. /// <returns></returns>
  774. private static DataTable createRegionSettingsTable()
  775. {
  776. DataTable regionsettings = new DataTable("regionsettings");
  777. createCol(regionsettings, "regionUUID", typeof(String));
  778. createCol(regionsettings, "block_terraform", typeof (Int32));
  779. createCol(regionsettings, "block_fly", typeof (Int32));
  780. createCol(regionsettings, "allow_damage", typeof (Int32));
  781. createCol(regionsettings, "restrict_pushing", typeof (Int32));
  782. createCol(regionsettings, "allow_land_resell", typeof (Int32));
  783. createCol(regionsettings, "allow_land_join_divide", typeof (Int32));
  784. createCol(regionsettings, "block_show_in_search", typeof (Int32));
  785. createCol(regionsettings, "agent_limit", typeof (Int32));
  786. createCol(regionsettings, "object_bonus", typeof (Double));
  787. createCol(regionsettings, "maturity", typeof (Int32));
  788. createCol(regionsettings, "disable_scripts", typeof (Int32));
  789. createCol(regionsettings, "disable_collisions", typeof (Int32));
  790. createCol(regionsettings, "disable_physics", typeof (Int32));
  791. createCol(regionsettings, "terrain_texture_1", typeof(String));
  792. createCol(regionsettings, "terrain_texture_2", typeof(String));
  793. createCol(regionsettings, "terrain_texture_3", typeof(String));
  794. createCol(regionsettings, "terrain_texture_4", typeof(String));
  795. createCol(regionsettings, "elevation_1_nw", typeof (Double));
  796. createCol(regionsettings, "elevation_2_nw", typeof (Double));
  797. createCol(regionsettings, "elevation_1_ne", typeof (Double));
  798. createCol(regionsettings, "elevation_2_ne", typeof (Double));
  799. createCol(regionsettings, "elevation_1_se", typeof (Double));
  800. createCol(regionsettings, "elevation_2_se", typeof (Double));
  801. createCol(regionsettings, "elevation_1_sw", typeof (Double));
  802. createCol(regionsettings, "elevation_2_sw", typeof (Double));
  803. createCol(regionsettings, "water_height", typeof (Double));
  804. createCol(regionsettings, "terrain_raise_limit", typeof (Double));
  805. createCol(regionsettings, "terrain_lower_limit", typeof (Double));
  806. createCol(regionsettings, "use_estate_sun", typeof (Int32));
  807. createCol(regionsettings, "sandbox", typeof (Int32));
  808. createCol(regionsettings, "fixed_sun", typeof (Int32));
  809. createCol(regionsettings, "sun_position", typeof (Double));
  810. createCol(regionsettings, "covenant", typeof(String));
  811. regionsettings.PrimaryKey = new DataColumn[] {regionsettings.Columns["RegionUUID"]};
  812. return regionsettings;
  813. }
  814. /// <summary>
  815. /// Create the "prims" table
  816. /// </summary>
  817. /// <returns></returns>
  818. private static DataTable createPrimTable()
  819. {
  820. DataTable prims = new DataTable("prims");
  821. createCol(prims, "UUID", typeof (String));
  822. createCol(prims, "RegionUUID", typeof (String));
  823. createCol(prims, "ParentID", typeof (Int32));
  824. createCol(prims, "CreationDate", typeof (Int32));
  825. createCol(prims, "Name", typeof (String));
  826. createCol(prims, "SceneGroupID", typeof (String));
  827. // various text fields
  828. createCol(prims, "Text", typeof (String));
  829. createCol(prims, "Description", typeof (String));
  830. createCol(prims, "SitName", typeof (String));
  831. createCol(prims, "TouchName", typeof (String));
  832. // permissions
  833. createCol(prims, "ObjectFlags", typeof (Int32));
  834. createCol(prims, "CreatorID", typeof (String));
  835. createCol(prims, "OwnerID", typeof (String));
  836. createCol(prims, "GroupID", typeof (String));
  837. createCol(prims, "LastOwnerID", typeof (String));
  838. createCol(prims, "OwnerMask", typeof (Int32));
  839. createCol(prims, "NextOwnerMask", typeof (Int32));
  840. createCol(prims, "GroupMask", typeof (Int32));
  841. createCol(prims, "EveryoneMask", typeof (Int32));
  842. createCol(prims, "BaseMask", typeof (Int32));
  843. // vectors
  844. createCol(prims, "PositionX", typeof (Double));
  845. createCol(prims, "PositionY", typeof (Double));
  846. createCol(prims, "PositionZ", typeof (Double));
  847. createCol(prims, "GroupPositionX", typeof (Double));
  848. createCol(prims, "GroupPositionY", typeof (Double));
  849. createCol(prims, "GroupPositionZ", typeof (Double));
  850. createCol(prims, "VelocityX", typeof (Double));
  851. createCol(prims, "VelocityY", typeof (Double));
  852. createCol(prims, "VelocityZ", typeof (Double));
  853. createCol(prims, "AngularVelocityX", typeof (Double));
  854. createCol(prims, "AngularVelocityY", typeof (Double));
  855. createCol(prims, "AngularVelocityZ", typeof (Double));
  856. createCol(prims, "AccelerationX", typeof (Double));
  857. createCol(prims, "AccelerationY", typeof (Double));
  858. createCol(prims, "AccelerationZ", typeof (Double));
  859. // quaternions
  860. createCol(prims, "RotationX", typeof (Double));
  861. createCol(prims, "RotationY", typeof (Double));
  862. createCol(prims, "RotationZ", typeof (Double));
  863. createCol(prims, "RotationW", typeof (Double));
  864. // sit target
  865. createCol(prims, "SitTargetOffsetX", typeof (Double));
  866. createCol(prims, "SitTargetOffsetY", typeof (Double));
  867. createCol(prims, "SitTargetOffsetZ", typeof (Double));
  868. createCol(prims, "SitTargetOrientW", typeof (Double));
  869. createCol(prims, "SitTargetOrientX", typeof (Double));
  870. createCol(prims, "SitTargetOrientY", typeof (Double));
  871. createCol(prims, "SitTargetOrientZ", typeof (Double));
  872. // Add in contraints
  873. prims.PrimaryKey = new DataColumn[] {prims.Columns["UUID"]};
  874. return prims;
  875. }
  876. /// <summary>
  877. /// Create the "land" table
  878. /// </summary>
  879. /// <returns></returns>
  880. private static DataTable createLandTable()
  881. {
  882. DataTable land = new DataTable("land");
  883. createCol(land, "UUID", typeof (String));
  884. createCol(land, "RegionUUID", typeof (String));
  885. createCol(land, "LocalLandID", typeof (Int32));
  886. // Bitmap is a byte[512]
  887. createCol(land, "Bitmap", typeof (Byte[]));
  888. createCol(land, "Name", typeof (String));
  889. createCol(land, "Description", typeof (String));
  890. createCol(land, "OwnerUUID", typeof (String));
  891. createCol(land, "IsGroupOwned", typeof (Int32));
  892. createCol(land, "Area", typeof (Int32));
  893. createCol(land, "AuctionID", typeof (Int32)); //Unemplemented
  894. createCol(land, "Category", typeof (Int32)); //Enum libsecondlife.Parcel.ParcelCategory
  895. createCol(land, "ClaimDate", typeof (Int32));
  896. createCol(land, "ClaimPrice", typeof (Int32));
  897. createCol(land, "GroupUUID", typeof (String));
  898. createCol(land, "SalePrice", typeof (Int32));
  899. createCol(land, "LandStatus", typeof (Int32)); //Enum. libsecondlife.Parcel.ParcelStatus
  900. createCol(land, "LandFlags", typeof (Int32));
  901. createCol(land, "LandingType", typeof (Int32));
  902. createCol(land, "MediaAutoScale", typeof (Int32));
  903. createCol(land, "MediaTextureUUID", typeof (String));
  904. createCol(land, "MediaURL", typeof (String));
  905. createCol(land, "MusicURL", typeof (String));
  906. createCol(land, "PassHours", typeof (Double));
  907. createCol(land, "PassPrice", typeof (Int32));
  908. createCol(land, "SnapshotUUID", typeof (String));
  909. createCol(land, "UserLocationX", typeof (Double));
  910. createCol(land, "UserLocationY", typeof (Double));
  911. createCol(land, "UserLocationZ", typeof (Double));
  912. createCol(land, "UserLookAtX", typeof (Double));
  913. createCol(land, "UserLookAtY", typeof (Double));
  914. createCol(land, "UserLookAtZ", typeof (Double));
  915. createCol(land, "AuthBuyerID", typeof (String));
  916. land.PrimaryKey = new DataColumn[] {land.Columns["UUID"]};
  917. return land;
  918. }
  919. /// <summary>
  920. /// Create the "landaccesslist" table
  921. /// </summary>
  922. /// <returns></returns>
  923. private static DataTable createLandAccessListTable()
  924. {
  925. DataTable landaccess = new DataTable("landaccesslist");
  926. createCol(landaccess, "LandUUID", typeof (String));
  927. createCol(landaccess, "AccessUUID", typeof (String));
  928. createCol(landaccess, "Flags", typeof (Int32));
  929. return landaccess;
  930. }
  931. /// <summary>
  932. /// Create the "primshapes" table
  933. /// </summary>
  934. /// <returns></returns>
  935. private static DataTable createShapeTable()
  936. {
  937. DataTable shapes = new DataTable("primshapes");
  938. createCol(shapes, "UUID", typeof (String));
  939. // shape is an enum
  940. createCol(shapes, "Shape", typeof (Int32));
  941. // vectors
  942. createCol(shapes, "ScaleX", typeof (Double));
  943. createCol(shapes, "ScaleY", typeof (Double));
  944. createCol(shapes, "ScaleZ", typeof (Double));
  945. // paths
  946. createCol(shapes, "PCode", typeof (Int32));
  947. createCol(shapes, "PathBegin", typeof (Int32));
  948. createCol(shapes, "PathEnd", typeof (Int32));
  949. createCol(shapes, "PathScaleX", typeof (Int32));
  950. createCol(shapes, "PathScaleY", typeof (Int32));
  951. createCol(shapes, "PathShearX", typeof (Int32));
  952. createCol(shapes, "PathShearY", typeof (Int32));
  953. createCol(shapes, "PathSkew", typeof (Int32));
  954. createCol(shapes, "PathCurve", typeof (Int32));
  955. createCol(shapes, "PathRadiusOffset", typeof (Int32));
  956. createCol(shapes, "PathRevolutions", typeof (Int32));
  957. createCol(shapes, "PathTaperX", typeof (Int32));
  958. createCol(shapes, "PathTaperY", typeof (Int32));
  959. createCol(shapes, "PathTwist", typeof (Int32));
  960. createCol(shapes, "PathTwistBegin", typeof (Int32));
  961. // profile
  962. createCol(shapes, "ProfileBegin", typeof (Int32));
  963. createCol(shapes, "ProfileEnd", typeof (Int32));
  964. createCol(shapes, "ProfileCurve", typeof (Int32));
  965. createCol(shapes, "ProfileHollow", typeof (Int32));
  966. createCol(shapes, "State", typeof(Int32));
  967. createCol(shapes, "Texture", typeof (Byte[]));
  968. createCol(shapes, "ExtraParams", typeof (Byte[]));
  969. shapes.PrimaryKey = new DataColumn[] {shapes.Columns["UUID"]};
  970. return shapes;
  971. }
  972. /// <summary>
  973. /// Create the "primitems" table
  974. /// </summary>
  975. /// <returns></returns>
  976. private static DataTable createItemsTable()
  977. {
  978. DataTable items = new DataTable("primitems");
  979. createCol(items, "itemID", typeof (String));
  980. createCol(items, "primID", typeof (String));
  981. createCol(items, "assetID", typeof (String));
  982. createCol(items, "parentFolderID", typeof (String));
  983. createCol(items, "invType", typeof (Int32));
  984. createCol(items, "assetType", typeof (Int32));
  985. createCol(items, "name", typeof (String));
  986. createCol(items, "description", typeof (String));
  987. createCol(items, "creationDate", typeof (Int64));
  988. createCol(items, "creatorID", typeof (String));
  989. createCol(items, "ownerID", typeof (String));
  990. createCol(items, "lastOwnerID", typeof (String));
  991. createCol(items, "groupID", typeof (String));
  992. createCol(items, "nextPermissions", typeof (Int32));
  993. createCol(items, "currentPermissions", typeof (Int32));
  994. createCol(items, "basePermissions", typeof (Int32));
  995. createCol(items, "everyonePermissions", typeof (Int32));
  996. createCol(items, "groupPermissions", typeof (Int32));
  997. createCol(items, "flags", typeof (Int32));
  998. items.PrimaryKey = new DataColumn[] {items.Columns["itemID"]};
  999. return items;
  1000. }
  1001. /***********************************************************************
  1002. *
  1003. * Convert between ADO.NET <=> OpenSim Objects
  1004. *
  1005. * These should be database independant
  1006. *
  1007. **********************************************************************/
  1008. /// <summary>
  1009. ///
  1010. /// </summary>
  1011. /// <param name="row"></param>
  1012. /// <returns></returns>
  1013. private SceneObjectPart buildPrim(DataRow row)
  1014. {
  1015. SceneObjectPart prim = new SceneObjectPart();
  1016. prim.UUID = new LLUUID((String) row["UUID"]);
  1017. // explicit conversion of integers is required, which sort
  1018. // of sucks. No idea if there is a shortcut here or not.
  1019. prim.ParentID = Convert.ToUInt32(row["ParentID"]);
  1020. prim.CreationDate = Convert.ToInt32(row["CreationDate"]);
  1021. prim.Name = (String) row["Name"];
  1022. // various text fields
  1023. prim.Text = (String) row["Text"];
  1024. prim.Description = (String) row["Description"];
  1025. prim.SitName = (String) row["SitName"];
  1026. prim.TouchName = (String) row["TouchName"];
  1027. // permissions
  1028. prim.ObjectFlags = Convert.ToUInt32(row["ObjectFlags"]);
  1029. prim.CreatorID = new LLUUID((String) row["CreatorID"]);
  1030. prim.OwnerID = new LLUUID((String) row["OwnerID"]);
  1031. prim.GroupID = new LLUUID((String) row["GroupID"]);
  1032. prim.LastOwnerID = new LLUUID((String) row["LastOwnerID"]);
  1033. prim.OwnerMask = Convert.ToUInt32(row["OwnerMask"]);
  1034. prim.NextOwnerMask = Convert.ToUInt32(row["NextOwnerMask"]);
  1035. prim.GroupMask = Convert.ToUInt32(row["GroupMask"]);
  1036. prim.EveryoneMask = Convert.ToUInt32(row["EveryoneMask"]);
  1037. prim.BaseMask = Convert.ToUInt32(row["BaseMask"]);
  1038. // vectors
  1039. prim.OffsetPosition = new LLVector3(
  1040. Convert.ToSingle(row["PositionX"]),
  1041. Convert.ToSingle(row["PositionY"]),
  1042. Convert.ToSingle(row["PositionZ"])
  1043. );
  1044. prim.GroupPosition = new LLVector3(
  1045. Convert.ToSingle(row["GroupPositionX"]),
  1046. Convert.ToSingle(row["GroupPositionY"]),
  1047. Convert.ToSingle(row["GroupPositionZ"])
  1048. );
  1049. prim.Velocity = new LLVector3(
  1050. Convert.ToSingle(row["VelocityX"]),
  1051. Convert.ToSingle(row["VelocityY"]),
  1052. Convert.ToSingle(row["VelocityZ"])
  1053. );
  1054. prim.AngularVelocity = new LLVector3(
  1055. Convert.ToSingle(row["AngularVelocityX"]),
  1056. Convert.ToSingle(row["AngularVelocityY"]),
  1057. Convert.ToSingle(row["AngularVelocityZ"])
  1058. );
  1059. prim.Acceleration = new LLVector3(
  1060. Convert.ToSingle(row["AccelerationX"]),
  1061. Convert.ToSingle(row["AccelerationY"]),
  1062. Convert.ToSingle(row["AccelerationZ"])
  1063. );
  1064. // quaternions
  1065. prim.RotationOffset = new LLQuaternion(
  1066. Convert.ToSingle(row["RotationX"]),
  1067. Convert.ToSingle(row["RotationY"]),
  1068. Convert.ToSingle(row["RotationZ"]),
  1069. Convert.ToSingle(row["RotationW"])
  1070. );
  1071. try
  1072. {
  1073. prim.SitTargetPositionLL = new LLVector3(
  1074. Convert.ToSingle(row["SitTargetOffsetX"]),
  1075. Convert.ToSingle(row["SitTargetOffsetY"]),
  1076. Convert.ToSingle(row["SitTargetOffsetZ"]));
  1077. prim.SitTargetOrientationLL = new LLQuaternion(
  1078. Convert.ToSingle(
  1079. row["SitTargetOrientX"]),
  1080. Convert.ToSingle(
  1081. row["SitTargetOrientY"]),
  1082. Convert.ToSingle(
  1083. row["SitTargetOrientZ"]),
  1084. Convert.ToSingle(
  1085. row["SitTargetOrientW"]));
  1086. }
  1087. catch (InvalidCastException)
  1088. {
  1089. // Database table was created before we got here and needs to be created! :P
  1090. lock (m_dataSet)
  1091. {
  1092. using (
  1093. MySqlCommand cmd =
  1094. new MySqlCommand(
  1095. "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;",
  1096. m_connection))
  1097. {
  1098. cmd.ExecuteNonQuery();
  1099. }
  1100. }
  1101. }
  1102. return prim;
  1103. }
  1104. /// <summary>
  1105. /// Build a prim inventory item from the persisted data.
  1106. /// </summary>
  1107. /// <param name="row"></param>
  1108. /// <returns></returns>
  1109. private static TaskInventoryItem buildItem(DataRow row)
  1110. {
  1111. TaskInventoryItem taskItem = new TaskInventoryItem();
  1112. taskItem.ItemID = new LLUUID((String)row["itemID"]);
  1113. taskItem.ParentPartID = new LLUUID((String)row["primID"]);
  1114. taskItem.AssetID = new LLUUID((String)row["assetID"]);
  1115. taskItem.ParentID = new LLUUID((String)row["parentFolderID"]);
  1116. taskItem.InvType = Convert.ToInt32(row["invType"]);
  1117. taskItem.Type = Convert.ToInt32(row["assetType"]);
  1118. taskItem.Name = (String)row["name"];
  1119. taskItem.Description = (String)row["description"];
  1120. taskItem.CreationDate = Convert.ToUInt32(row["creationDate"]);
  1121. taskItem.CreatorID = new LLUUID((String)row["creatorID"]);
  1122. taskItem.OwnerID = new LLUUID((String)row["ownerID"]);
  1123. taskItem.LastOwnerID = new LLUUID((String)row["lastOwnerID"]);
  1124. taskItem.GroupID = new LLUUID((String)row["groupID"]);
  1125. taskItem.NextOwnerMask = Convert.ToUInt32(row["nextPermissions"]);
  1126. taskItem.OwnerMask = Convert.ToUInt32(row["currentPermissions"]);
  1127. taskItem.BaseMask = Convert.ToUInt32(row["basePermissions"]);
  1128. taskItem.EveryoneMask = Convert.ToUInt32(row["everyonePermissions"]);
  1129. taskItem.GroupMask = Convert.ToUInt32(row["groupPermissions"]);
  1130. taskItem.Flags = Convert.ToUInt32(row["flags"]);
  1131. return taskItem;
  1132. }
  1133. private static RegionSettings buildRegionSettings(DataRow row)
  1134. {
  1135. RegionSettings newSettings = new RegionSettings();
  1136. newSettings.RegionUUID = new LLUUID((string) row["regionUUID"]);
  1137. newSettings.BlockTerraform = Convert.ToBoolean(row["block_terraform"]);
  1138. newSettings.AllowDamage = Convert.ToBoolean(row["allow_damage"]);
  1139. newSettings.BlockFly = Convert.ToBoolean(row["block_fly"]);
  1140. newSettings.RestrictPushing = Convert.ToBoolean(row["restrict_pushing"]);
  1141. newSettings.AllowLandResell = Convert.ToBoolean(row["allow_land_resell"]);
  1142. newSettings.AllowLandJoinDivide = Convert.ToBoolean(row["allow_land_join_divide"]);
  1143. newSettings.BlockShowInSearch = Convert.ToBoolean(row["block_show_in_search"]);
  1144. newSettings.AgentLimit = Convert.ToInt32(row["agent_limit"]);
  1145. newSettings.ObjectBonus = Convert.ToDouble(row["object_bonus"]);
  1146. newSettings.Maturity = Convert.ToInt32(row["maturity"]);
  1147. newSettings.DisableScripts = Convert.ToBoolean(row["disable_scripts"]);
  1148. newSettings.DisableCollisions = Convert.ToBoolean(row["disable_collisions"]);
  1149. newSettings.DisablePhysics = Convert.ToBoolean(row["disable_physics"]);
  1150. newSettings.TerrainTexture1 = new LLUUID((String) row["terrain_texture_1"]);
  1151. newSettings.TerrainTexture2 = new LLUUID((String) row["terrain_texture_2"]);
  1152. newSettings.TerrainTexture3 = new LLUUID((String) row["terrain_texture_3"]);
  1153. newSettings.TerrainTexture4 = new LLUUID((String) row["terrain_texture_4"]);
  1154. newSettings.Elevation1NW = Convert.ToDouble(row["elevation_1_nw"]);
  1155. newSettings.Elevation2NW = Convert.ToDouble(row["elevation_2_nw"]);
  1156. newSettings.Elevation1NE = Convert.ToDouble(row["elevation_1_ne"]);
  1157. newSettings.Elevation2NE = Convert.ToDouble(row["elevation_2_ne"]);
  1158. newSettings.Elevation1SE = Convert.ToDouble(row["elevation_1_se"]);
  1159. newSettings.Elevation2SE = Convert.ToDouble(row["elevation_2_se"]);
  1160. newSettings.Elevation1SW = Convert.ToDouble(row["elevation_1_sw"]);
  1161. newSettings.Elevation2SW = Convert.ToDouble(row["elevation_2_sw"]);
  1162. newSettings.WaterHeight = Convert.ToDouble(row["water_height"]);
  1163. newSettings.TerrainRaiseLimit = Convert.ToDouble(row["terrain_raise_limit"]);
  1164. newSettings.TerrainLowerLimit = Convert.ToDouble(row["terrain_lower_limit"]);
  1165. newSettings.UseEstateSun = Convert.ToBoolean(row["use_estate_sun"]);
  1166. newSettings.Sandbox = Convert.ToBoolean(row["sandbox"]);
  1167. newSettings.FixedSun = Convert.ToBoolean(row["fixed_sun"]);
  1168. newSettings.SunPosition = Convert.ToDouble(row["sun_position"]);
  1169. newSettings.Covenant = new LLUUID((String) row["covenant"]);
  1170. return newSettings;
  1171. }
  1172. /// <summary>
  1173. ///
  1174. /// </summary>
  1175. /// <param name="row"></param>
  1176. /// <returns></returns>
  1177. private static LandData buildLandData(DataRow row)
  1178. {
  1179. LandData newData = new LandData();
  1180. newData.globalID = new LLUUID((String) row["UUID"]);
  1181. newData.localID = Convert.ToInt32(row["LocalLandID"]);
  1182. // Bitmap is a byte[512]
  1183. newData.landBitmapByteArray = (Byte[]) row["Bitmap"];
  1184. newData.landName = (String) row["Name"];
  1185. newData.landDesc = (String) row["Description"];
  1186. newData.ownerID = (String) row["OwnerUUID"];
  1187. newData.isGroupOwned = Convert.ToBoolean(row["IsGroupOwned"]);
  1188. newData.area = Convert.ToInt32(row["Area"]);
  1189. newData.auctionID = Convert.ToUInt32(row["AuctionID"]); //Unemplemented
  1190. newData.category = (Parcel.ParcelCategory) Convert.ToInt32(row["Category"]);
  1191. //Enum libsecondlife.Parcel.ParcelCategory
  1192. newData.claimDate = Convert.ToInt32(row["ClaimDate"]);
  1193. newData.claimPrice = Convert.ToInt32(row["ClaimPrice"]);
  1194. newData.groupID = new LLUUID((String) row["GroupUUID"]);
  1195. newData.salePrice = Convert.ToInt32(row["SalePrice"]);
  1196. newData.landStatus = (Parcel.ParcelStatus) Convert.ToInt32(row["LandStatus"]);
  1197. //Enum. libsecondlife.Parcel.ParcelStatus
  1198. newData.landFlags = Convert.ToUInt32(row["LandFlags"]);
  1199. newData.landingType = Convert.ToByte(row["LandingType"]);
  1200. newData.mediaAutoScale = Convert.ToByte(row["MediaAutoScale"]);
  1201. newData.mediaID = new LLUUID((String) row["MediaTextureUUID"]);
  1202. newData.mediaURL = (String) row["MediaURL"];
  1203. newData.musicURL = (String) row["MusicURL"];
  1204. newData.passHours = Convert.ToSingle(row["PassHours"]);
  1205. newData.passPrice = Convert.ToInt32(row["PassPrice"]);
  1206. LLUUID authedbuyer = LLUUID.Zero;
  1207. LLUUID snapshotID = LLUUID.Zero;
  1208. Helpers.TryParse((string)row["AuthBuyerID"], out authedbuyer);
  1209. Helpers.TryParse((string)row["SnapshotUUID"], out snapshotID);
  1210. newData.authBuyerID = authedbuyer;
  1211. newData.snapshotID = snapshotID;
  1212. try
  1213. {
  1214. newData.userLocation =
  1215. new LLVector3(Convert.ToSingle(row["UserLocationX"]), Convert.ToSingle(row["UserLocationY"]),
  1216. Convert.ToSingle(row["UserLocationZ"]));
  1217. newData.userLookAt =
  1218. new LLVector3(Convert.ToSingle(row["UserLookAtX"]), Convert.ToSingle(row["UserLookAtY"]),
  1219. Convert.ToSingle(row["UserLookAtZ"]));
  1220. }
  1221. catch (InvalidCastException)
  1222. {
  1223. newData.userLocation = LLVector3.Zero;
  1224. newData.userLookAt = LLVector3.Zero;
  1225. m_log.ErrorFormat("[PARCEL]: unable to get parcel telehub settings for {1}", newData.landName);
  1226. }
  1227. newData.parcelAccessList = new List<ParcelManager.ParcelAccessEntry>();
  1228. return newData;
  1229. }
  1230. /// <summary>
  1231. ///
  1232. /// </summary>
  1233. /// <param name="row"></param>
  1234. /// <returns></returns>
  1235. private static ParcelManager.ParcelAccessEntry buildLandAccessData(DataRow row)
  1236. {
  1237. ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry();
  1238. entry.AgentID = new LLUUID((string) row["AccessUUID"]);
  1239. entry.Flags = (ParcelManager.AccessList) Convert.ToInt32(row["Flags"]);
  1240. entry.Time = new DateTime();
  1241. return entry;
  1242. }
  1243. /// <summary>
  1244. ///
  1245. /// </summary>
  1246. /// <param name="val"></param>
  1247. /// <returns></returns>
  1248. private static Array serializeTerrain(double[,] val)
  1249. {
  1250. MemoryStream str = new MemoryStream(65536*sizeof (double));
  1251. BinaryWriter bw = new BinaryWriter(str);
  1252. // TODO: COMPATIBILITY - Add byte-order conversions
  1253. for (int x = 0; x < 256; x++)
  1254. for (int y = 0; y < 256; y++)
  1255. {
  1256. double height = val[x, y];
  1257. if (height == 0.0)
  1258. height = double.Epsilon;
  1259. bw.Write(height);
  1260. }
  1261. return str.ToArray();
  1262. }
  1263. /// <summary>
  1264. ///
  1265. /// </summary>
  1266. /// <param name="row"></param>
  1267. /// <param name="prim"></param>
  1268. /// <param name="sceneGroupID"></param>
  1269. /// <param name="regionUUID"></param>
  1270. private void fillPrimRow(DataRow row, SceneObjectPart prim, LLUUID sceneGroupID, LLUUID regionUUID)
  1271. {
  1272. row["UUID"] = Util.ToRawUuidString(prim.UUID);
  1273. row["RegionUUID"] = Util.ToRawUuidString(regionUUID);
  1274. row["ParentID"] = prim.ParentID;
  1275. row["CreationDate"] = prim.CreationDate;
  1276. row["Name"] = prim.Name;
  1277. row["SceneGroupID"] = Util.ToRawUuidString(sceneGroupID);
  1278. // the UUID of the root part for this SceneObjectGroup
  1279. // various text fields
  1280. row["Text"] = prim.Text;
  1281. row["Description"] = prim.Description;
  1282. row["SitName"] = prim.SitName;
  1283. row["TouchName"] = prim.TouchName;
  1284. // permissions
  1285. row["ObjectFlags"] = prim.ObjectFlags;
  1286. row["CreatorID"] = Util.ToRawUuidString(prim.CreatorID);
  1287. row["OwnerID"] = Util.ToRawUuidString(prim.OwnerID);
  1288. row["GroupID"] = Util.ToRawUuidString(prim.GroupID);
  1289. row["LastOwnerID"] = Util.ToRawUuidString(prim.LastOwnerID);
  1290. row["OwnerMask"] = prim.OwnerMask;
  1291. row["NextOwnerMask"] = prim.NextOwnerMask;
  1292. row["GroupMask"] = prim.GroupMask;
  1293. row["EveryoneMask"] = prim.EveryoneMask;
  1294. row["BaseMask"] = prim.BaseMask;
  1295. // vectors
  1296. row["PositionX"] = prim.OffsetPosition.X;
  1297. row["PositionY"] = prim.OffsetPosition.Y;
  1298. row["PositionZ"] = prim.OffsetPosition.Z;
  1299. row["GroupPositionX"] = prim.GroupPosition.X;
  1300. row["GroupPositionY"] = prim.GroupPosition.Y;
  1301. row["GroupPositionZ"] = prim.GroupPosition.Z;
  1302. row["VelocityX"] = prim.Velocity.X;
  1303. row["VelocityY"] = prim.Velocity.Y;
  1304. row["VelocityZ"] = prim.Velocity.Z;
  1305. row["AngularVelocityX"] = prim.AngularVelocity.X;
  1306. row["AngularVelocityY"] = prim.AngularVelocity.Y;
  1307. row["AngularVelocityZ"] = prim.AngularVelocity.Z;
  1308. row["AccelerationX"] = prim.Acceleration.X;
  1309. row["AccelerationY"] = prim.Acceleration.Y;
  1310. row["AccelerationZ"] = prim.Acceleration.Z;
  1311. // quaternions
  1312. row["RotationX"] = prim.RotationOffset.X;
  1313. row["RotationY"] = prim.RotationOffset.Y;
  1314. row["RotationZ"] = prim.RotationOffset.Z;
  1315. row["RotationW"] = prim.RotationOffset.W;
  1316. try
  1317. {
  1318. // Sit target
  1319. LLVector3 sitTargetPos = prim.SitTargetPositionLL;
  1320. row["SitTargetOffsetX"] = sitTargetPos.X;
  1321. row["SitTargetOffsetY"] = sitTargetPos.Y;
  1322. row["SitTargetOffsetZ"] = sitTargetPos.Z;
  1323. LLQuaternion sitTargetOrient = prim.SitTargetOrientationLL;
  1324. row["SitTargetOrientW"] = sitTargetOrient.W;
  1325. row["SitTargetOrientX"] = sitTargetOrient.X;
  1326. row["SitTargetOrientY"] = sitTargetOrient.Y;
  1327. row["SitTargetOrientZ"] = sitTargetOrient.Z;
  1328. }
  1329. catch (MySqlException)
  1330. {
  1331. // Database table was created before we got here and needs to be created! :P
  1332. using (
  1333. MySqlCommand cmd =
  1334. new MySqlCommand(
  1335. "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;",
  1336. m_connection))
  1337. {
  1338. cmd.ExecuteNonQuery();
  1339. }
  1340. }
  1341. }
  1342. /// <summary>
  1343. ///
  1344. /// </summary>
  1345. /// <param name="row"></param>
  1346. /// <param name="taskItem"></param>
  1347. private static void fillItemRow(DataRow row, TaskInventoryItem taskItem)
  1348. {
  1349. row["itemID"] = taskItem.ItemID;
  1350. row["primID"] = taskItem.ParentPartID;
  1351. row["assetID"] = taskItem.AssetID;
  1352. row["parentFolderID"] = taskItem.ParentID;
  1353. row["invType"] = taskItem.InvType;
  1354. row["assetType"] = taskItem.Type;
  1355. row["name"] = taskItem.Name;
  1356. row["description"] = taskItem.Description;
  1357. row["creationDate"] = taskItem.CreationDate;
  1358. row["creatorID"] = taskItem.CreatorID;
  1359. row["ownerID"] = taskItem.OwnerID;
  1360. row["lastOwnerID"] = taskItem.LastOwnerID;
  1361. row["groupID"] = taskItem.GroupID;
  1362. row["nextPermissions"] = taskItem.NextOwnerMask;
  1363. row["currentPermissions"] = taskItem.OwnerMask;
  1364. row["basePermissions"] = taskItem.BaseMask;
  1365. row["everyonePermissions"] = taskItem.EveryoneMask;
  1366. row["groupPermissions"] = taskItem.GroupMask;
  1367. row["flags"] = taskItem.Flags;
  1368. }
  1369. /// <summary>
  1370. ///
  1371. /// </summary>
  1372. private static void fillRegionSettingsRow(DataRow row, RegionSettings settings)
  1373. {
  1374. row["regionUUID"] = settings.RegionUUID.ToString();
  1375. row["block_terraform"] = settings.BlockTerraform;
  1376. row["block_fly"] = settings.BlockFly;
  1377. row["allow_damage"] = settings.AllowDamage;
  1378. row["restrict_pushing"] = settings.RestrictPushing;
  1379. row["allow_land_resell"] = settings.AllowLandResell;
  1380. row["allow_land_join_divide"] = settings.AllowLandJoinDivide;
  1381. row["block_show_in_search"] = settings.BlockShowInSearch;
  1382. row["agent_limit"] = settings.AgentLimit;
  1383. row["object_bonus"] = settings.ObjectBonus;
  1384. row["maturity"] = settings.Maturity;
  1385. row["disable_scripts"] = settings.DisableScripts;
  1386. row["disable_collisions"] = settings.DisableCollisions;
  1387. row["disable_physics"] = settings.DisablePhysics;
  1388. row["terrain_texture_1"] = settings.TerrainTexture1.ToString();
  1389. row["terrain_texture_2"] = settings.TerrainTexture2.ToString();
  1390. row["terrain_texture_3"] = settings.TerrainTexture3.ToString();
  1391. row["terrain_texture_4"] = settings.TerrainTexture4.ToString();
  1392. row["elevation_1_nw"] = settings.Elevation1NW;
  1393. row["elevation_2_nw"] = settings.Elevation2NW;
  1394. row["elevation_1_ne"] = settings.Elevation1NE;
  1395. row["elevation_2_ne"] = settings.Elevation2NE;
  1396. row["elevation_1_se"] = settings.Elevation1SE;
  1397. row["elevation_2_se"] = settings.Elevation2SE;
  1398. row["elevation_1_sw"] = settings.Elevation1SW;
  1399. row["elevation_2_sw"] = settings.Elevation2SW;
  1400. row["water_height"] = settings.WaterHeight;
  1401. row["terrain_raise_limit"] = settings.TerrainRaiseLimit;
  1402. row["terrain_lower_limit"] = settings.TerrainLowerLimit;
  1403. row["use_estate_sun"] = settings.UseEstateSun;
  1404. row["sandbox"] = settings.Sandbox;
  1405. row["fixed_sun"] = settings.FixedSun;
  1406. row["sun_position"] = settings.SunPosition;
  1407. row["covenant"] = settings.Covenant.ToString();
  1408. }
  1409. /// <summary>
  1410. ///
  1411. /// </summary>
  1412. /// <param name="row"></param>
  1413. /// <param name="land"></param>
  1414. /// <param name="regionUUID"></param>
  1415. private static void fillLandRow(DataRow row, LandData land, LLUUID regionUUID)
  1416. {
  1417. row["UUID"] = Util.ToRawUuidString(land.globalID);
  1418. row["RegionUUID"] = Util.ToRawUuidString(regionUUID);
  1419. row["LocalLandID"] = land.localID;
  1420. // Bitmap is a byte[512]
  1421. row["Bitmap"] = land.landBitmapByteArray;
  1422. row["Name"] = land.landName;
  1423. row["Description"] = land.landDesc;
  1424. row["OwnerUUID"] = Util.ToRawUuidString(land.ownerID);
  1425. row["IsGroupOwned"] = land.isGroupOwned;
  1426. row["Area"] = land.area;
  1427. row["AuctionID"] = land.auctionID; //Unemplemented
  1428. row["Category"] = land.category; //Enum libsecondlife.Parcel.ParcelCategory
  1429. row["ClaimDate"] = land.claimDate;
  1430. row["ClaimPrice"] = land.claimPrice;
  1431. row["GroupUUID"] = Util.ToRawUuidString(land.groupID);
  1432. row["SalePrice"] = land.salePrice;
  1433. row["LandStatus"] = land.landStatus; //Enum. libsecondlife.Parcel.ParcelStatus
  1434. row["LandFlags"] = land.landFlags;
  1435. row["LandingType"] = land.landingType;
  1436. row["MediaAutoScale"] = land.mediaAutoScale;
  1437. row["MediaTextureUUID"] = Util.ToRawUuidString(land.mediaID);
  1438. row["MediaURL"] = land.mediaURL;
  1439. row["MusicURL"] = land.musicURL;
  1440. row["PassHours"] = land.passHours;
  1441. row["PassPrice"] = land.passPrice;
  1442. row["SnapshotUUID"] = Util.ToRawUuidString(land.snapshotID);
  1443. row["UserLocationX"] = land.userLocation.X;
  1444. row["UserLocationY"] = land.userLocation.Y;
  1445. row["UserLocationZ"] = land.userLocation.Z;
  1446. row["UserLookAtX"] = land.userLookAt.X;
  1447. row["UserLookAtY"] = land.userLookAt.Y;
  1448. row["UserLookAtZ"] = land.userLookAt.Z;
  1449. row["AuthBuyerID"] = land.authBuyerID;
  1450. }
  1451. /// <summary>
  1452. ///
  1453. /// </summary>
  1454. /// <param name="row"></param>
  1455. /// <param name="entry"></param>
  1456. /// <param name="parcelID"></param>
  1457. private static void fillLandAccessRow(DataRow row, ParcelManager.ParcelAccessEntry entry, LLUUID parcelID)
  1458. {
  1459. row["LandUUID"] = Util.ToRawUuidString(parcelID);
  1460. row["AccessUUID"] = Util.ToRawUuidString(entry.AgentID);
  1461. row["Flags"] = entry.Flags;
  1462. }
  1463. /// <summary>
  1464. ///
  1465. /// </summary>
  1466. /// <param name="row"></param>
  1467. /// <returns></returns>
  1468. private PrimitiveBaseShape buildShape(DataRow row)
  1469. {
  1470. PrimitiveBaseShape s = new PrimitiveBaseShape();
  1471. s.Scale = new LLVector3(
  1472. Convert.ToSingle(row["ScaleX"]),
  1473. Convert.ToSingle(row["ScaleY"]),
  1474. Convert.ToSingle(row["ScaleZ"])
  1475. );
  1476. // paths
  1477. s.PCode = Convert.ToByte(row["PCode"]);
  1478. s.PathBegin = Convert.ToUInt16(row["PathBegin"]);
  1479. s.PathEnd = Convert.ToUInt16(row["PathEnd"]);
  1480. s.PathScaleX = Convert.ToByte(row["PathScaleX"]);
  1481. s.PathScaleY = Convert.ToByte(row["PathScaleY"]);
  1482. s.PathShearX = Convert.ToByte(row["PathShearX"]);
  1483. s.PathShearY = Convert.ToByte(row["PathShearY"]);
  1484. s.PathSkew = Convert.ToSByte(row["PathSkew"]);
  1485. s.PathCurve = Convert.ToByte(row["PathCurve"]);
  1486. s.PathRadiusOffset = Convert.ToSByte(row["PathRadiusOffset"]);
  1487. s.PathRevolutions = Convert.ToByte(row["PathRevolutions"]);
  1488. s.PathTaperX = Convert.ToSByte(row["PathTaperX"]);
  1489. s.PathTaperY = Convert.ToSByte(row["PathTaperY"]);
  1490. s.PathTwist = Convert.ToSByte(row["PathTwist"]);
  1491. s.PathTwistBegin = Convert.ToSByte(row["PathTwistBegin"]);
  1492. // profile
  1493. s.ProfileBegin = Convert.ToUInt16(row["ProfileBegin"]);
  1494. s.ProfileEnd = Convert.ToUInt16(row["ProfileEnd"]);
  1495. s.ProfileCurve = Convert.ToByte(row["ProfileCurve"]);
  1496. s.ProfileHollow = Convert.ToUInt16(row["ProfileHollow"]);
  1497. byte[] textureEntry = (byte[]) row["Texture"];
  1498. s.TextureEntry = textureEntry;
  1499. s.ExtraParams = (byte[]) row["ExtraParams"];
  1500. try
  1501. {
  1502. s.State = Convert.ToByte(row["State"]);
  1503. }
  1504. catch (InvalidCastException)
  1505. {
  1506. // Database table was created before we got here and needs to be created! :P
  1507. lock (m_dataSet)
  1508. {
  1509. using (
  1510. MySqlCommand cmd =
  1511. new MySqlCommand(
  1512. "ALTER TABLE `primshapes` ADD COLUMN `State` int NOT NULL default 0;",
  1513. m_connection))
  1514. {
  1515. cmd.ExecuteNonQuery();
  1516. }
  1517. }
  1518. }
  1519. return s;
  1520. }
  1521. /// <summary>
  1522. ///
  1523. /// </summary>
  1524. /// <param name="row"></param>
  1525. /// <param name="prim"></param>
  1526. private void fillShapeRow(DataRow row, SceneObjectPart prim)
  1527. {
  1528. PrimitiveBaseShape s = prim.Shape;
  1529. row["UUID"] = Util.ToRawUuidString(prim.UUID);
  1530. // shape is an enum
  1531. row["Shape"] = 0;
  1532. // vectors
  1533. row["ScaleX"] = s.Scale.X;
  1534. row["ScaleY"] = s.Scale.Y;
  1535. row["ScaleZ"] = s.Scale.Z;
  1536. // paths
  1537. row["PCode"] = s.PCode;
  1538. row["PathBegin"] = s.PathBegin;
  1539. row["PathEnd"] = s.PathEnd;
  1540. row["PathScaleX"] = s.PathScaleX;
  1541. row["PathScaleY"] = s.PathScaleY;
  1542. row["PathShearX"] = s.PathShearX;
  1543. row["PathShearY"] = s.PathShearY;
  1544. row["PathSkew"] = s.PathSkew;
  1545. row["PathCurve"] = s.PathCurve;
  1546. row["PathRadiusOffset"] = s.PathRadiusOffset;
  1547. row["PathRevolutions"] = s.PathRevolutions;
  1548. row["PathTaperX"] = s.PathTaperX;
  1549. row["PathTaperY"] = s.PathTaperY;
  1550. row["PathTwist"] = s.PathTwist;
  1551. row["PathTwistBegin"] = s.PathTwistBegin;
  1552. // profile
  1553. row["ProfileBegin"] = s.ProfileBegin;
  1554. row["ProfileEnd"] = s.ProfileEnd;
  1555. row["ProfileCurve"] = s.ProfileCurve;
  1556. row["ProfileHollow"] = s.ProfileHollow;
  1557. row["Texture"] = s.TextureEntry;
  1558. row["ExtraParams"] = s.ExtraParams;
  1559. try
  1560. {
  1561. row["State"] = s.State;
  1562. }
  1563. catch (MySqlException)
  1564. {
  1565. lock (m_dataSet)
  1566. {
  1567. // Database table was created before we got here and needs to be created! :P
  1568. using (
  1569. MySqlCommand cmd =
  1570. new MySqlCommand(
  1571. "ALTER TABLE `primshapes` ADD COLUMN `State` int NOT NULL default 0;",
  1572. m_connection))
  1573. {
  1574. cmd.ExecuteNonQuery();
  1575. }
  1576. }
  1577. }
  1578. }
  1579. /// <summary>
  1580. ///
  1581. /// </summary>
  1582. /// <param name="prim"></param>
  1583. /// <param name="sceneGroupID"></param>
  1584. /// <param name="regionUUID"></param>
  1585. private void addPrim(SceneObjectPart prim, LLUUID sceneGroupID, LLUUID regionUUID)
  1586. {
  1587. lock (m_dataSet)
  1588. {
  1589. DataTable prims = m_dataSet.Tables["prims"];
  1590. DataTable shapes = m_dataSet.Tables["primshapes"];
  1591. DataRow primRow = prims.Rows.Find(Util.ToRawUuidString(prim.UUID));
  1592. if (primRow == null)
  1593. {
  1594. primRow = prims.NewRow();
  1595. fillPrimRow(primRow, prim, sceneGroupID, regionUUID);
  1596. prims.Rows.Add(primRow);
  1597. }
  1598. else
  1599. {
  1600. fillPrimRow(primRow, prim, sceneGroupID, regionUUID);
  1601. }
  1602. DataRow shapeRow = shapes.Rows.Find(Util.ToRawUuidString(prim.UUID));
  1603. if (shapeRow == null)
  1604. {
  1605. shapeRow = shapes.NewRow();
  1606. fillShapeRow(shapeRow, prim);
  1607. shapes.Rows.Add(shapeRow);
  1608. }
  1609. else
  1610. {
  1611. fillShapeRow(shapeRow, prim);
  1612. }
  1613. }
  1614. }
  1615. /// <summary>
  1616. /// see IRegionDatastore
  1617. /// </summary>
  1618. /// <param name="primID"></param>
  1619. /// <param name="items"></param>
  1620. public void StorePrimInventory(LLUUID primID, ICollection<TaskInventoryItem> items)
  1621. {
  1622. if (!persistPrimInventories)
  1623. return;
  1624. m_log.InfoFormat("[REGION DB]: Persisting Prim Inventory with prim ID {0}", primID);
  1625. // For now, we're just going to crudely remove all the previous inventory items
  1626. // no matter whether they have changed or not, and replace them with the current set.
  1627. lock (m_dataSet)
  1628. {
  1629. RemoveItems(primID);
  1630. // repalce with current inventory details
  1631. foreach (TaskInventoryItem newItem in items)
  1632. {
  1633. // m_log.InfoFormat(
  1634. // "[REGION DB]: " +
  1635. // "Adding item {0}, {1} to prim ID {2}",
  1636. // newItem.Name, newItem.ItemID, newItem.ParentPartID);
  1637. DataRow newItemRow = m_itemsTable.NewRow();
  1638. fillItemRow(newItemRow, newItem);
  1639. m_itemsTable.Rows.Add(newItemRow);
  1640. }
  1641. }
  1642. Commit();
  1643. }
  1644. /***********************************************************************
  1645. *
  1646. * SQL Statement Creation Functions
  1647. *
  1648. * These functions create SQL statements for update, insert, and create.
  1649. * They can probably be factored later to have a db independant
  1650. * portion and a db specific portion
  1651. *
  1652. **********************************************************************/
  1653. /// <summary>
  1654. /// Create a MySQL insert command
  1655. /// </summary>
  1656. /// <param name="table"></param>
  1657. /// <param name="dt"></param>
  1658. /// <returns></returns>
  1659. /// <remarks>
  1660. /// This is subtle enough to deserve some commentary.
  1661. /// Instead of doing *lots* and *lots of hardcoded strings
  1662. /// for database definitions we'll use the fact that
  1663. /// realistically all insert statements look like "insert
  1664. /// into A(b, c) values(:b, :c) on the parameterized query
  1665. /// front. If we just have a list of b, c, etc... we can
  1666. /// generate these strings instead of typing them out.
  1667. /// </remarks>
  1668. private static MySqlCommand createInsertCommand(string table, DataTable dt)
  1669. {
  1670. string[] cols = new string[dt.Columns.Count];
  1671. for (int i = 0; i < dt.Columns.Count; i++)
  1672. {
  1673. DataColumn col = dt.Columns[i];
  1674. cols[i] = col.ColumnName;
  1675. }
  1676. string sql = "insert into " + table + "(";
  1677. sql += String.Join(", ", cols);
  1678. // important, the first ':' needs to be here, the rest get added in the join
  1679. sql += ") values (?";
  1680. sql += String.Join(", ?", cols);
  1681. sql += ")";
  1682. MySqlCommand cmd = new MySqlCommand(sql);
  1683. // this provides the binding for all our parameters, so
  1684. // much less code than it used to be
  1685. foreach (DataColumn col in dt.Columns)
  1686. {
  1687. cmd.Parameters.Add(createMySqlParameter(col.ColumnName, col.DataType));
  1688. }
  1689. return cmd;
  1690. }
  1691. /// <summary>
  1692. /// Create a MySQL update command
  1693. /// </summary>
  1694. /// <param name="table"></param>
  1695. /// <param name="pk"></param>
  1696. /// <param name="dt"></param>
  1697. /// <returns></returns>
  1698. private static MySqlCommand createUpdateCommand(string table, string pk, DataTable dt)
  1699. {
  1700. string sql = "update " + table + " set ";
  1701. string subsql = String.Empty;
  1702. foreach (DataColumn col in dt.Columns)
  1703. {
  1704. if (subsql.Length > 0)
  1705. {
  1706. // a map function would rock so much here
  1707. subsql += ", ";
  1708. }
  1709. subsql += col.ColumnName + "=?" + col.ColumnName;
  1710. }
  1711. sql += subsql;
  1712. sql += " where " + pk;
  1713. MySqlCommand cmd = new MySqlCommand(sql);
  1714. // this provides the binding for all our parameters, so
  1715. // much less code than it used to be
  1716. foreach (DataColumn col in dt.Columns)
  1717. {
  1718. cmd.Parameters.Add(createMySqlParameter(col.ColumnName, col.DataType));
  1719. }
  1720. return cmd;
  1721. }
  1722. /// <summary>
  1723. ///
  1724. /// </summary>
  1725. /// <param name="dt"></param>
  1726. /// <returns></returns>
  1727. // private static string defineTable(DataTable dt)
  1728. // {
  1729. // string sql = "create table " + dt.TableName + "(";
  1730. // string subsql = String.Empty;
  1731. // foreach (DataColumn col in dt.Columns)
  1732. // {
  1733. // if (subsql.Length > 0)
  1734. // {
  1735. // // a map function would rock so much here
  1736. // subsql += ",\n";
  1737. // }
  1738. // subsql += col.ColumnName + " " + MySqlType(col.DataType);
  1739. // if (dt.PrimaryKey.Length > 0 && col == dt.PrimaryKey[0])
  1740. // {
  1741. // subsql += " primary key";
  1742. // }
  1743. // }
  1744. // sql += subsql;
  1745. // sql += ")";
  1746. // //m_log.InfoFormat("[DATASTORE]: defineTable() sql {0}", sql);
  1747. // return sql;
  1748. // }
  1749. /***********************************************************************
  1750. *
  1751. * Database Binding functions
  1752. *
  1753. * These will be db specific due to typing, and minor differences
  1754. * in databases.
  1755. *
  1756. **********************************************************************/
  1757. ///<summary>
  1758. /// <para>This is a convenience function that collapses 5 repetitive
  1759. /// lines for defining MySqlParameters to 2 parameters:
  1760. /// column name and database type.
  1761. /// </para>
  1762. /// <para>
  1763. /// It assumes certain conventions like ?param as the param
  1764. /// name to replace in parametrized queries, and that source
  1765. /// version is always current version, both of which are fine
  1766. /// for us.
  1767. /// </para>
  1768. /// </summary>
  1769. /// <returns>a built MySql parameter</returns>
  1770. private static MySqlParameter createMySqlParameter(string name, Type type)
  1771. {
  1772. MySqlParameter param = new MySqlParameter();
  1773. param.ParameterName = "?" + name;
  1774. param.DbType = dbtypeFromType(type);
  1775. param.SourceColumn = name;
  1776. param.SourceVersion = DataRowVersion.Current;
  1777. return param;
  1778. }
  1779. /// <summary>
  1780. ///
  1781. /// </summary>
  1782. /// <param name="da"></param>
  1783. /// <param name="conn"></param>
  1784. private void SetupPrimCommands(MySqlDataAdapter da, MySqlConnection conn)
  1785. {
  1786. MySqlCommand insertCommand = createInsertCommand("prims", m_primTable);
  1787. insertCommand.Connection = conn;
  1788. da.InsertCommand = insertCommand;
  1789. MySqlCommand updateCommand = createUpdateCommand("prims", "UUID=?UUID", m_primTable);
  1790. updateCommand.Connection = conn;
  1791. da.UpdateCommand = updateCommand;
  1792. MySqlCommand delete = new MySqlCommand("delete from prims where UUID=?UUID");
  1793. delete.Parameters.Add(createMySqlParameter("UUID", typeof (String)));
  1794. delete.Connection = conn;
  1795. da.DeleteCommand = delete;
  1796. }
  1797. /// <summary>
  1798. ///
  1799. /// </summary>
  1800. /// <param name="da"></param>
  1801. /// <param name="conn"></param>
  1802. private void SetupItemsCommands(MySqlDataAdapter da, MySqlConnection conn)
  1803. {
  1804. da.InsertCommand = createInsertCommand("primitems", m_itemsTable);
  1805. da.InsertCommand.Connection = conn;
  1806. da.UpdateCommand = createUpdateCommand("primitems", "itemID = ?itemID", m_itemsTable);
  1807. da.UpdateCommand.Connection = conn;
  1808. MySqlCommand delete = new MySqlCommand("delete from primitems where itemID = ?itemID");
  1809. delete.Parameters.Add(createMySqlParameter("itemID", typeof (String)));
  1810. delete.Connection = conn;
  1811. da.DeleteCommand = delete;
  1812. }
  1813. private void SetupRegionSettingsCommands(MySqlDataAdapter da, MySqlConnection conn)
  1814. {
  1815. da.InsertCommand = createInsertCommand("regionsettings", m_regionSettingsTable);
  1816. da.InsertCommand.Connection = conn;
  1817. da.UpdateCommand = createUpdateCommand("regionsettings", "regionUUID = ?regionUUID", m_regionSettingsTable);
  1818. da.UpdateCommand.Connection = conn;
  1819. MySqlCommand delete = new MySqlCommand("delete from regionsettings where regionUUID = ?regionUUID");
  1820. delete.Parameters.Add(createMySqlParameter("regionUUID", typeof(String)));
  1821. delete.Connection = conn;
  1822. da.DeleteCommand = delete;
  1823. }
  1824. /// <summary>
  1825. ///
  1826. /// </summary>
  1827. /// <param name="da"></param>
  1828. /// <param name="conn"></param>
  1829. private void SetupTerrainCommands(MySqlDataAdapter da, MySqlConnection conn)
  1830. {
  1831. da.InsertCommand = createInsertCommand("terrain", m_dataSet.Tables["terrain"]);
  1832. da.InsertCommand.Connection = conn;
  1833. }
  1834. /// <summary>
  1835. ///
  1836. /// </summary>
  1837. /// <param name="da"></param>
  1838. /// <param name="conn"></param>
  1839. private void setupLandCommands(MySqlDataAdapter da, MySqlConnection conn)
  1840. {
  1841. da.InsertCommand = createInsertCommand("land", m_dataSet.Tables["land"]);
  1842. da.InsertCommand.Connection = conn;
  1843. da.UpdateCommand = createUpdateCommand("land", "UUID=?UUID", m_dataSet.Tables["land"]);
  1844. da.UpdateCommand.Connection = conn;
  1845. }
  1846. /// <summary>
  1847. ///
  1848. /// </summary>
  1849. /// <param name="da"></param>
  1850. /// <param name="conn"></param>
  1851. private void setupLandAccessCommands(MySqlDataAdapter da, MySqlConnection conn)
  1852. {
  1853. da.InsertCommand = createInsertCommand("landaccesslist", m_dataSet.Tables["landaccesslist"]);
  1854. da.InsertCommand.Connection = conn;
  1855. }
  1856. /// <summary>
  1857. ///
  1858. /// </summary>
  1859. /// <param name="da"></param>
  1860. /// <param name="conn"></param>
  1861. private void SetupShapeCommands(MySqlDataAdapter da, MySqlConnection conn)
  1862. {
  1863. da.InsertCommand = createInsertCommand("primshapes", m_dataSet.Tables["primshapes"]);
  1864. da.InsertCommand.Connection = conn;
  1865. da.UpdateCommand = createUpdateCommand("primshapes", "UUID=?UUID", m_dataSet.Tables["primshapes"]);
  1866. da.UpdateCommand.Connection = conn;
  1867. MySqlCommand delete = new MySqlCommand("delete from primshapes where UUID = ?UUID");
  1868. delete.Parameters.Add(createMySqlParameter("UUID", typeof (String)));
  1869. delete.Connection = conn;
  1870. da.DeleteCommand = delete;
  1871. }
  1872. /// <summary>
  1873. ///
  1874. /// </summary>
  1875. /// <param name="conn">MySQL connection handler</param>
  1876. // private static void InitDB(MySqlConnection conn)
  1877. // {
  1878. // string createPrims = defineTable(createPrimTable());
  1879. // string createShapes = defineTable(createShapeTable());
  1880. // string createItems = defineTable(createItemsTable());
  1881. // string createTerrain = defineTable(createTerrainTable());
  1882. // // Land table is created from the Versionable Test Table routine now.
  1883. // //string createLand = defineTable(createLandTable());
  1884. // string createLandAccessList = defineTable(createLandAccessListTable());
  1885. // MySqlCommand pcmd = new MySqlCommand(createPrims, conn);
  1886. // MySqlCommand scmd = new MySqlCommand(createShapes, conn);
  1887. // MySqlCommand icmd = new MySqlCommand(createItems, conn);
  1888. // MySqlCommand tcmd = new MySqlCommand(createTerrain, conn);
  1889. // //MySqlCommand lcmd = new MySqlCommand(createLand, conn);
  1890. // MySqlCommand lalcmd = new MySqlCommand(createLandAccessList, conn);
  1891. // if (conn.State != ConnectionState.Open)
  1892. // {
  1893. // try
  1894. // {
  1895. // conn.Open();
  1896. // }
  1897. // catch (Exception ex)
  1898. // {
  1899. // m_log.Error("[REGION DB]: Error connecting to MySQL server: " + ex.Message);
  1900. // m_log.Error("[REGION DB]: Application is terminating!");
  1901. // Thread.CurrentThread.Abort();
  1902. // }
  1903. // }
  1904. // try
  1905. // {
  1906. // pcmd.ExecuteNonQuery();
  1907. // }
  1908. // catch (MySqlException e)
  1909. // {
  1910. // m_log.WarnFormat("[REGION DB]: Primitives Table Already Exists: {0}", e);
  1911. // }
  1912. // try
  1913. // {
  1914. // scmd.ExecuteNonQuery();
  1915. // }
  1916. // catch (MySqlException e)
  1917. // {
  1918. // m_log.WarnFormat("[REGION DB]: Shapes Table Already Exists: {0}", e);
  1919. // }
  1920. // try
  1921. // {
  1922. // icmd.ExecuteNonQuery();
  1923. // }
  1924. // catch (MySqlException e)
  1925. // {
  1926. // m_log.WarnFormat("[REGION DB]: Items Table Already Exists: {0}", e);
  1927. // }
  1928. // try
  1929. // {
  1930. // tcmd.ExecuteNonQuery();
  1931. // }
  1932. // catch (MySqlException e)
  1933. // {
  1934. // m_log.WarnFormat("[REGION DB]: Terrain Table Already Exists: {0}", e);
  1935. // }
  1936. // //try
  1937. // //{
  1938. // //lcmd.ExecuteNonQuery();
  1939. // //}
  1940. // //catch (MySqlException e)
  1941. // //{
  1942. // //m_log.WarnFormat("[MySql]: Land Table Already Exists: {0}", e);
  1943. // //}
  1944. // try
  1945. // {
  1946. // lalcmd.ExecuteNonQuery();
  1947. // }
  1948. // catch (MySqlException e)
  1949. // {
  1950. // m_log.WarnFormat("[REGION DB]: LandAccessList Table Already Exists: {0}", e);
  1951. // }
  1952. // conn.Close();
  1953. // }
  1954. /// <summary>
  1955. ///
  1956. /// </summary>
  1957. /// <param name="conn"></param>
  1958. /// <param name="m"></param>
  1959. /// <returns></returns>
  1960. private bool TestTables(MySqlConnection conn, Migration m)
  1961. {
  1962. // we already have migrations, get out of here
  1963. if (m.Version > 0)
  1964. return false;
  1965. MySqlCommand primSelectCmd = new MySqlCommand(m_primSelect, conn);
  1966. MySqlDataAdapter pDa = new MySqlDataAdapter(primSelectCmd);
  1967. MySqlCommand shapeSelectCmd = new MySqlCommand(m_shapeSelect, conn);
  1968. MySqlDataAdapter sDa = new MySqlDataAdapter(shapeSelectCmd);
  1969. MySqlCommand itemsSelectCmd = new MySqlCommand(m_itemsSelect, conn);
  1970. MySqlDataAdapter iDa = new MySqlDataAdapter(itemsSelectCmd);
  1971. MySqlCommand terrainSelectCmd = new MySqlCommand(m_terrainSelect, conn);
  1972. MySqlDataAdapter tDa = new MySqlDataAdapter(terrainSelectCmd);
  1973. MySqlCommand landSelectCmd = new MySqlCommand(m_landSelect, conn);
  1974. MySqlDataAdapter lDa = new MySqlDataAdapter(landSelectCmd);
  1975. MySqlCommand landAccessListSelectCmd = new MySqlCommand(m_landAccessListSelect, conn);
  1976. MySqlDataAdapter lalDa = new MySqlDataAdapter(landAccessListSelectCmd);
  1977. DataSet tmpDS = new DataSet();
  1978. try
  1979. {
  1980. pDa.Fill(tmpDS, "prims");
  1981. sDa.Fill(tmpDS, "primshapes");
  1982. iDa.Fill(tmpDS, "primitems");
  1983. tDa.Fill(tmpDS, "terrain");
  1984. lDa.Fill(tmpDS, "land");
  1985. lalDa.Fill(tmpDS, "landaccesslist");
  1986. }
  1987. catch (MySqlException)
  1988. {
  1989. m_log.Info("[DATASTORE]: MySql Database doesn't exist... creating");
  1990. return false;
  1991. }
  1992. // we have tables, but not a migration model yet
  1993. if (m.Version == 0)
  1994. m.Version = 1;
  1995. return true;
  1996. // pDa.Fill(tmpDS, "prims");
  1997. // sDa.Fill(tmpDS, "primshapes");
  1998. // if (persistPrimInventories)
  1999. // iDa.Fill(tmpDS, "primitems");
  2000. // tDa.Fill(tmpDS, "terrain");
  2001. // lDa.Fill(tmpDS, "land");
  2002. // lalDa.Fill(tmpDS, "landaccesslist");
  2003. // foreach (DataColumn col in createPrimTable().Columns)
  2004. // {
  2005. // if (!tmpDS.Tables["prims"].Columns.Contains(col.ColumnName))
  2006. // {
  2007. // m_log.Info("[REGION DB]: Missing required column:" + col.ColumnName);
  2008. // return false;
  2009. // }
  2010. // }
  2011. // foreach (DataColumn col in createShapeTable().Columns)
  2012. // {
  2013. // if (!tmpDS.Tables["primshapes"].Columns.Contains(col.ColumnName))
  2014. // {
  2015. // m_log.Info("[REGION DB]: Missing required column:" + col.ColumnName);
  2016. // return false;
  2017. // }
  2018. // }
  2019. // // XXX primitems should probably go here eventually
  2020. // foreach (DataColumn col in createTerrainTable().Columns)
  2021. // {
  2022. // if (!tmpDS.Tables["terrain"].Columns.Contains(col.ColumnName))
  2023. // {
  2024. // m_log.Info("[REGION DB]: Missing require column:" + col.ColumnName);
  2025. // return false;
  2026. // }
  2027. // }
  2028. // foreach (DataColumn col in createLandTable().Columns)
  2029. // {
  2030. // if (!tmpDS.Tables["land"].Columns.Contains(col.ColumnName))
  2031. // {
  2032. // m_log.Info("[REGION DB]: Missing require column:" + col.ColumnName);
  2033. // return false;
  2034. // }
  2035. // }
  2036. // foreach (DataColumn col in createLandAccessListTable().Columns)
  2037. // {
  2038. // if (!tmpDS.Tables["landaccesslist"].Columns.Contains(col.ColumnName))
  2039. // {
  2040. // m_log.Info("[DATASTORE]: Missing require column:" + col.ColumnName);
  2041. // return false;
  2042. // }
  2043. // }
  2044. // return true;
  2045. }
  2046. /***********************************************************************
  2047. *
  2048. * Type conversion functions
  2049. *
  2050. **********************************************************************/
  2051. /// <summary>
  2052. /// Type conversion functions
  2053. /// </summary>
  2054. /// <param name="type"></param>
  2055. /// <returns></returns>
  2056. private static DbType dbtypeFromType(Type type)
  2057. {
  2058. if (type == typeof (String))
  2059. {
  2060. return DbType.String;
  2061. }
  2062. else if (type == typeof (Int32))
  2063. {
  2064. return DbType.Int32;
  2065. }
  2066. else if (type == typeof (Double))
  2067. {
  2068. return DbType.Double;
  2069. }
  2070. else if (type == typeof (Byte))
  2071. {
  2072. return DbType.Byte;
  2073. }
  2074. else if (type == typeof (Double))
  2075. {
  2076. return DbType.Double;
  2077. }
  2078. else if (type == typeof (Byte[]))
  2079. {
  2080. return DbType.Binary;
  2081. }
  2082. else
  2083. {
  2084. return DbType.String;
  2085. }
  2086. }
  2087. /// <summary>
  2088. /// </summary>
  2089. /// <param name="type"></param>
  2090. /// <returns></returns>
  2091. /// <remarks>this is something we'll need to implement for each db slightly differently.</remarks>
  2092. // private static string MySqlType(Type type)
  2093. // {
  2094. // if (type == typeof (String))
  2095. // {
  2096. // return "varchar(255)";
  2097. // }
  2098. // else if (type == typeof (Int32))
  2099. // {
  2100. // return "integer";
  2101. // }
  2102. // else if (type == typeof (Int64))
  2103. // {
  2104. // return "bigint";
  2105. // }
  2106. // else if (type == typeof (Double))
  2107. // {
  2108. // return "float";
  2109. // }
  2110. // else if (type == typeof (Byte[]))
  2111. // {
  2112. // return "longblob";
  2113. // }
  2114. // else
  2115. // {
  2116. // return "string";
  2117. // }
  2118. // }
  2119. }
  2120. }