MSSQLAssetData.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. private string m_connectionString;
  50. #region IPlugin Members
  51. override public void Dispose() { }
  52. /// <summary>
  53. /// <para>Initialises asset interface</para>
  54. /// </summary>
  55. // [Obsolete("Cannot be default-initialized!")]
  56. override public void Initialise()
  57. {
  58. m_log.Info("[MSSQLAssetData]: " + Name + " cannot be default-initialized!");
  59. throw new PluginNotInitialisedException(Name);
  60. }
  61. /// <summary>
  62. /// Initialises asset interface
  63. /// </summary>
  64. /// <para>
  65. /// a string instead of file, if someone writes the support
  66. /// </para>
  67. /// <param name="connectionString">connect string</param>
  68. override public void Initialise(string connectionString)
  69. {
  70. m_ticksToEpoch = new System.DateTime(1970, 1, 1).Ticks;
  71. m_database = new MSSQLManager(connectionString);
  72. m_connectionString = connectionString;
  73. //New migration to check for DB changes
  74. m_database.CheckMigration(_migrationStore);
  75. }
  76. /// <summary>
  77. /// Database provider version.
  78. /// </summary>
  79. override public string Version
  80. {
  81. get { return m_database.getVersion(); }
  82. }
  83. /// <summary>
  84. /// The name of this DB provider.
  85. /// </summary>
  86. override public string Name
  87. {
  88. get { return "MSSQL Asset storage engine"; }
  89. }
  90. #endregion
  91. #region IAssetDataPlugin Members
  92. /// <summary>
  93. /// Fetch Asset from m_database
  94. /// </summary>
  95. /// <param name="assetID">the asset UUID</param>
  96. /// <returns></returns>
  97. override public AssetBase GetAsset(UUID assetID)
  98. {
  99. string sql = "SELECT * FROM assets WHERE id = @id";
  100. using (SqlConnection conn = new SqlConnection(m_connectionString))
  101. using (SqlCommand cmd = new SqlCommand(sql, conn))
  102. {
  103. cmd.Parameters.Add(m_database.CreateParameter("id", assetID));
  104. conn.Open();
  105. using (SqlDataReader reader = cmd.ExecuteReader())
  106. {
  107. if (reader.Read())
  108. {
  109. AssetBase asset = new AssetBase(
  110. DBGuid.FromDB(reader["id"]),
  111. (string)reader["name"],
  112. Convert.ToSByte(reader["assetType"]),
  113. reader["creatorid"].ToString()
  114. );
  115. // Region Main
  116. asset.Description = (string)reader["description"];
  117. asset.Local = Convert.ToBoolean(reader["local"]);
  118. asset.Temporary = Convert.ToBoolean(reader["temporary"]);
  119. asset.Flags = (AssetFlags)(Convert.ToInt32(reader["asset_flags"]));
  120. asset.Data = (byte[])reader["data"];
  121. return asset;
  122. }
  123. return null; // throw new Exception("No rows to return");
  124. }
  125. }
  126. }
  127. /// <summary>
  128. /// Create asset in m_database
  129. /// </summary>
  130. /// <param name="asset">the asset</param>
  131. override public void StoreAsset(AssetBase asset)
  132. {
  133. string sql =
  134. @"IF EXISTS(SELECT * FROM assets WHERE id=@id)
  135. UPDATE assets set name = @name, description = @description, assetType = @assetType,
  136. local = @local, temporary = @temporary, creatorid = @creatorid, data = @data
  137. WHERE id=@id
  138. ELSE
  139. INSERT INTO assets
  140. ([id], [name], [description], [assetType], [local],
  141. [temporary], [create_time], [access_time], [creatorid], [asset_flags], [data])
  142. VALUES
  143. (@id, @name, @description, @assetType, @local,
  144. @temporary, @create_time, @access_time, @creatorid, @asset_flags, @data)";
  145. string assetName = asset.Name;
  146. if (asset.Name.Length > AssetBase.MAX_ASSET_NAME)
  147. {
  148. assetName = asset.Name.Substring(0, AssetBase.MAX_ASSET_NAME);
  149. m_log.WarnFormat(
  150. "[ASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add",
  151. asset.Name, asset.ID, asset.Name.Length, assetName.Length);
  152. }
  153. string assetDescription = asset.Description;
  154. if (asset.Description.Length > AssetBase.MAX_ASSET_DESC)
  155. {
  156. assetDescription = asset.Description.Substring(0, AssetBase.MAX_ASSET_DESC);
  157. m_log.WarnFormat(
  158. "[ASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add",
  159. asset.Description, asset.ID, asset.Description.Length, assetDescription.Length);
  160. }
  161. using (SqlConnection conn = new SqlConnection(m_connectionString))
  162. using (SqlCommand command = new SqlCommand(sql, conn))
  163. {
  164. int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000);
  165. command.Parameters.Add(m_database.CreateParameter("id", asset.FullID));
  166. command.Parameters.Add(m_database.CreateParameter("name", assetName));
  167. command.Parameters.Add(m_database.CreateParameter("description", assetDescription));
  168. command.Parameters.Add(m_database.CreateParameter("assetType", asset.Type));
  169. command.Parameters.Add(m_database.CreateParameter("local", asset.Local));
  170. command.Parameters.Add(m_database.CreateParameter("temporary", asset.Temporary));
  171. command.Parameters.Add(m_database.CreateParameter("access_time", now));
  172. command.Parameters.Add(m_database.CreateParameter("create_time", now));
  173. command.Parameters.Add(m_database.CreateParameter("asset_flags", (int)asset.Flags));
  174. command.Parameters.Add(m_database.CreateParameter("creatorid", asset.Metadata.CreatorID));
  175. command.Parameters.Add(m_database.CreateParameter("data", asset.Data));
  176. conn.Open();
  177. try
  178. {
  179. command.ExecuteNonQuery();
  180. }
  181. catch(Exception e)
  182. {
  183. m_log.Error("[ASSET DB]: Error storing item :" + e.Message);
  184. }
  185. }
  186. }
  187. // Commented out since currently unused - this probably should be called in GetAsset()
  188. // private void UpdateAccessTime(AssetBase asset)
  189. // {
  190. // using (AutoClosingSqlCommand cmd = m_database.Query("UPDATE assets SET access_time = @access_time WHERE id=@id"))
  191. // {
  192. // int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000);
  193. // cmd.Parameters.AddWithValue("@id", asset.FullID.ToString());
  194. // cmd.Parameters.AddWithValue("@access_time", now);
  195. // try
  196. // {
  197. // cmd.ExecuteNonQuery();
  198. // }
  199. // catch (Exception e)
  200. // {
  201. // m_log.Error(e.ToString());
  202. // }
  203. // }
  204. // }
  205. /// <summary>
  206. /// Check if the assets exist in the database.
  207. /// </summary>
  208. /// <param name="uuids">The assets' IDs</param>
  209. /// <returns>For each asset: true if it exists, false otherwise</returns>
  210. public override bool[] AssetsExist(UUID[] uuids)
  211. {
  212. if (uuids.Length == 0)
  213. return new bool[0];
  214. HashSet<UUID> exist = new HashSet<UUID>();
  215. string ids = "'" + string.Join("','", uuids) + "'";
  216. string sql = string.Format("SELECT id FROM assets WHERE id IN ({0})", ids);
  217. using (SqlConnection conn = new SqlConnection(m_connectionString))
  218. using (SqlCommand cmd = new SqlCommand(sql, conn))
  219. {
  220. conn.Open();
  221. using (SqlDataReader reader = cmd.ExecuteReader())
  222. {
  223. while (reader.Read())
  224. {
  225. UUID id = DBGuid.FromDB(reader["id"]);
  226. exist.Add(id);
  227. }
  228. }
  229. }
  230. bool[] results = new bool[uuids.Length];
  231. for (int i = 0; i < uuids.Length; i++)
  232. results[i] = exist.Contains(uuids[i]);
  233. return results;
  234. }
  235. /// <summary>
  236. /// Returns a list of AssetMetadata objects. The list is a subset of
  237. /// the entire data set offset by <paramref name="start" /> containing
  238. /// <paramref name="count" /> elements.
  239. /// </summary>
  240. /// <param name="start">The number of results to discard from the total data set.</param>
  241. /// <param name="count">The number of rows the returned list should contain.</param>
  242. /// <returns>A list of AssetMetadata objects.</returns>
  243. public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
  244. {
  245. List<AssetMetadata> retList = new List<AssetMetadata>(count);
  246. string sql = @"WITH OrderedAssets AS
  247. (
  248. SELECT id, name, description, assetType, temporary, creatorid,
  249. RowNumber = ROW_NUMBER() OVER (ORDER BY id)
  250. FROM assets
  251. )
  252. SELECT *
  253. FROM OrderedAssets
  254. WHERE RowNumber BETWEEN @start AND @stop;";
  255. using (SqlConnection conn = new SqlConnection(m_connectionString))
  256. using (SqlCommand cmd = new SqlCommand(sql, conn))
  257. {
  258. cmd.Parameters.Add(m_database.CreateParameter("start", start));
  259. cmd.Parameters.Add(m_database.CreateParameter("stop", start + count - 1));
  260. conn.Open();
  261. using (SqlDataReader reader = cmd.ExecuteReader())
  262. {
  263. while (reader.Read())
  264. {
  265. AssetMetadata metadata = new AssetMetadata();
  266. metadata.FullID = DBGuid.FromDB(reader["id"]);
  267. metadata.Name = (string)reader["name"];
  268. metadata.Description = (string)reader["description"];
  269. metadata.Type = Convert.ToSByte(reader["assetType"]);
  270. metadata.Temporary = Convert.ToBoolean(reader["temporary"]);
  271. metadata.CreatorID = (string)reader["creatorid"];
  272. retList.Add(metadata);
  273. }
  274. }
  275. }
  276. return retList;
  277. }
  278. public override bool Delete(string id)
  279. {
  280. return false;
  281. }
  282. #endregion
  283. }
  284. }