MySQLDataStore.cs 103 KB

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