1
0

MSSQLAssetData.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 OpenSimulator 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.Data;
  29. using System.Data.SqlClient;
  30. using System.Reflection;
  31. using System.Collections.Generic;
  32. using OpenMetaverse;
  33. using log4net;
  34. using OpenSim.Framework;
  35. namespace OpenSim.Data.MSSQL
  36. {
  37. /// <summary>
  38. /// A MSSQL Interface for the Asset server
  39. /// </summary>
  40. public class MSSQLAssetData : AssetDataBase
  41. {
  42. private const string _migrationStore = "AssetStore";
  43. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  44. private long m_ticksToEpoch;
  45. /// <summary>
  46. /// Database manager
  47. /// </summary>
  48. private MSSQLManager m_database;
  49. #region IPlugin Members
  50. override public void Dispose() { }
  51. /// <summary>
  52. /// <para>Initialises asset interface</para>
  53. /// </summary>
  54. // [Obsolete("Cannot be default-initialized!")]
  55. override public void Initialise()
  56. {
  57. m_log.Info("[MSSQLAssetData]: " + Name + " cannot be default-initialized!");
  58. throw new PluginNotInitialisedException(Name);
  59. }
  60. /// <summary>
  61. /// Initialises asset interface
  62. /// </summary>
  63. /// <para>
  64. /// a string instead of file, if someone writes the support
  65. /// </para>
  66. /// <param name="connectionString">connect string</param>
  67. override public void Initialise(string connectionString)
  68. {
  69. m_ticksToEpoch = new System.DateTime(1970, 1, 1).Ticks;
  70. if (!string.IsNullOrEmpty(connectionString))
  71. {
  72. m_database = new MSSQLManager(connectionString);
  73. }
  74. else
  75. {
  76. IniFile gridDataMSSqlFile = new IniFile("mssql_connection.ini");
  77. string settingDataSource = gridDataMSSqlFile.ParseFileReadValue("data_source");
  78. string settingInitialCatalog = gridDataMSSqlFile.ParseFileReadValue("initial_catalog");
  79. string settingPersistSecurityInfo = gridDataMSSqlFile.ParseFileReadValue("persist_security_info");
  80. string settingUserId = gridDataMSSqlFile.ParseFileReadValue("user_id");
  81. string settingPassword = gridDataMSSqlFile.ParseFileReadValue("password");
  82. m_database =
  83. new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId,
  84. settingPassword);
  85. }
  86. //New migration to check for DB changes
  87. m_database.CheckMigration(_migrationStore);
  88. }
  89. /// <summary>
  90. /// Database provider version.
  91. /// </summary>
  92. override public string Version
  93. {
  94. get { return m_database.getVersion(); }
  95. }
  96. /// <summary>
  97. /// The name of this DB provider.
  98. /// </summary>
  99. override public string Name
  100. {
  101. get { return "MSSQL Asset storage engine"; }
  102. }
  103. #endregion
  104. #region IAssetDataPlugin Members
  105. /// <summary>
  106. /// Fetch Asset from m_database
  107. /// </summary>
  108. /// <param name="assetID">the asset UUID</param>
  109. /// <returns></returns>
  110. override protected AssetBase FetchStoredAsset(UUID assetID)
  111. {
  112. string sql = "SELECT * FROM assets WHERE id = @id";
  113. using (AutoClosingSqlCommand command = m_database.Query(sql))
  114. {
  115. command.Parameters.Add(m_database.CreateParameter("id", assetID));
  116. using (SqlDataReader reader = command.ExecuteReader())
  117. {
  118. if (reader.Read())
  119. {
  120. AssetBase asset = new AssetBase();
  121. // Region Main
  122. asset.FullID = new UUID((Guid)reader["id"]);
  123. asset.Name = (string)reader["name"];
  124. asset.Description = (string)reader["description"];
  125. asset.Type = Convert.ToSByte(reader["assetType"]);
  126. asset.Local = Convert.ToBoolean(reader["local"]);
  127. asset.Temporary = Convert.ToBoolean(reader["temporary"]);
  128. asset.Data = (byte[])reader["data"];
  129. return asset;
  130. }
  131. return null; // throw new Exception("No rows to return");
  132. }
  133. }
  134. }
  135. /// <summary>
  136. /// Create asset in m_database
  137. /// </summary>
  138. /// <param name="asset">the asset</param>
  139. override public void CreateAsset(AssetBase asset)
  140. {
  141. if (ExistsAsset(asset.FullID))
  142. {
  143. return;
  144. }
  145. string sql = @"INSERT INTO assets
  146. ([id], [name], [description], [assetType], [local],
  147. [temporary], [create_time], [access_time], [data])
  148. VALUES
  149. (@id, @name, @description, @assetType, @local,
  150. @temporary, @create_time, @access_time, @data)";
  151. string assetName = asset.Name;
  152. if (asset.Name.Length > 64)
  153. {
  154. assetName = asset.Name.Substring(0, 64);
  155. m_log.Warn("[ASSET DB]: Name field truncated from " + asset.Name.Length + " to " + assetName.Length + " characters on add");
  156. }
  157. string assetDescription = asset.Description;
  158. if (asset.Description.Length > 64)
  159. {
  160. assetDescription = asset.Description.Substring(0, 64);
  161. m_log.Warn("[ASSET DB]: Description field truncated from " + asset.Description.Length + " to " + assetDescription.Length + " characters on add");
  162. }
  163. using (AutoClosingSqlCommand command = m_database.Query(sql))
  164. {
  165. int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000);
  166. command.Parameters.Add(m_database.CreateParameter("id", asset.FullID));
  167. command.Parameters.Add(m_database.CreateParameter("name", assetName));
  168. command.Parameters.Add(m_database.CreateParameter("description", assetDescription));
  169. command.Parameters.Add(m_database.CreateParameter("assetType", asset.Type));
  170. command.Parameters.Add(m_database.CreateParameter("local", asset.Local));
  171. command.Parameters.Add(m_database.CreateParameter("temporary", asset.Temporary));
  172. command.Parameters.Add(m_database.CreateParameter("access_time", now));
  173. command.Parameters.Add(m_database.CreateParameter("create_time", now));
  174. command.Parameters.Add(m_database.CreateParameter("data", asset.Data));
  175. try
  176. {
  177. command.ExecuteNonQuery();
  178. }
  179. catch(Exception e)
  180. {
  181. m_log.Error("[ASSET DB]: Error inserting item :" + e.Message);
  182. }
  183. }
  184. }
  185. /// <summary>
  186. /// Update asset in m_database
  187. /// </summary>
  188. /// <param name="asset">the asset</param>
  189. override public void UpdateAsset(AssetBase asset)
  190. {
  191. string sql = @"UPDATE assets set id = @id, name = @name, description = @description, assetType = @assetType,
  192. local = @local, temporary = @temporary, data = @data
  193. WHERE id = @keyId;";
  194. string assetName = asset.Name;
  195. if (asset.Name.Length > 64)
  196. {
  197. assetName = asset.Name.Substring(0, 64);
  198. m_log.Warn("[ASSET DB]: Name field truncated from " + asset.Name.Length + " to " + assetName.Length + " characters on update");
  199. }
  200. string assetDescription = asset.Description;
  201. if (asset.Description.Length > 64)
  202. {
  203. assetDescription = asset.Description.Substring(0, 64);
  204. m_log.Warn("[ASSET DB]: Description field truncated from " + asset.Description.Length + " to " + assetDescription.Length + " characters on update");
  205. }
  206. using (AutoClosingSqlCommand command = m_database.Query(sql))
  207. {
  208. command.Parameters.Add(m_database.CreateParameter("id", asset.FullID));
  209. command.Parameters.Add(m_database.CreateParameter("name", assetName));
  210. command.Parameters.Add(m_database.CreateParameter("description", assetDescription));
  211. command.Parameters.Add(m_database.CreateParameter("assetType", asset.Type));
  212. command.Parameters.Add(m_database.CreateParameter("local", asset.Local));
  213. command.Parameters.Add(m_database.CreateParameter("temporary", asset.Temporary));
  214. command.Parameters.Add(m_database.CreateParameter("data", asset.Data));
  215. command.Parameters.Add(m_database.CreateParameter("@keyId", asset.FullID));
  216. try
  217. {
  218. command.ExecuteNonQuery();
  219. }
  220. catch (Exception e)
  221. {
  222. m_log.Error(e.ToString());
  223. }
  224. }
  225. }
  226. // Commented out since currently unused - this probably should be called in FetchAsset()
  227. // private void UpdateAccessTime(AssetBase asset)
  228. // {
  229. // using (AutoClosingSqlCommand cmd = m_database.Query("UPDATE assets SET access_time = @access_time WHERE id=@id"))
  230. // {
  231. // int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000);
  232. // cmd.Parameters.AddWithValue("@id", asset.FullID.ToString());
  233. // cmd.Parameters.AddWithValue("@access_time", now);
  234. // try
  235. // {
  236. // cmd.ExecuteNonQuery();
  237. // }
  238. // catch (Exception e)
  239. // {
  240. // m_log.Error(e.ToString());
  241. // }
  242. // }
  243. // }
  244. /// <summary>
  245. /// Check if asset exist in m_database
  246. /// </summary>
  247. /// <param name="uuid"></param>
  248. /// <returns>true if exist.</returns>
  249. override public bool ExistsAsset(UUID uuid)
  250. {
  251. if (FetchAsset(uuid) != null)
  252. {
  253. return true;
  254. }
  255. return false;
  256. }
  257. /// <summary>
  258. /// Returns a list of AssetMetadata objects. The list is a subset of
  259. /// the entire data set offset by <paramref name="start" /> containing
  260. /// <paramref name="count" /> elements.
  261. /// </summary>
  262. /// <param name="start">The number of results to discard from the total data set.</param>
  263. /// <param name="count">The number of rows the returned list should contain.</param>
  264. /// <returns>A list of AssetMetadata objects.</returns>
  265. public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
  266. {
  267. List<AssetMetadata> retList = new List<AssetMetadata>(count);
  268. string sql = @"SELECT (name,description,assetType,temporary,id), Row = ROW_NUMBER()
  269. OVER (ORDER BY (some column to order by))
  270. WHERE Row >= @Start AND Row < @Start + @Count";
  271. using (AutoClosingSqlCommand command = m_database.Query(sql))
  272. {
  273. command.Parameters.Add(m_database.CreateParameter("start", start));
  274. command.Parameters.Add(m_database.CreateParameter("count", count));
  275. using (SqlDataReader reader = command.ExecuteReader())
  276. {
  277. while (reader.Read())
  278. {
  279. AssetMetadata metadata = new AssetMetadata();
  280. metadata.FullID = new UUID((Guid)reader["id"]);
  281. metadata.Name = (string)reader["name"];
  282. metadata.Description = (string)reader["description"];
  283. metadata.Type = Convert.ToSByte(reader["assetType"]);
  284. metadata.Temporary = Convert.ToBoolean(reader["temporary"]);
  285. }
  286. }
  287. }
  288. return retList;
  289. }
  290. #endregion
  291. }
  292. }