MSSQLGenericTableHandler.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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.Collections.Generic;
  29. using System.Data;
  30. using System.Reflection;
  31. using log4net;
  32. using System.Data.SqlClient;
  33. using OpenMetaverse;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.Framework.Interfaces;
  36. using System.Text;
  37. namespace OpenSim.Data.MSSQL
  38. {
  39. public class MSSQLGenericTableHandler<T> where T : class, new()
  40. {
  41. // private static readonly ILog m_log =
  42. // LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  43. protected string m_ConnectionString;
  44. protected MSSQLManager m_database; //used for parameter type translation
  45. protected Dictionary<string, FieldInfo> m_Fields =
  46. new Dictionary<string, FieldInfo>();
  47. protected List<string> m_ColumnNames = null;
  48. protected string m_Realm;
  49. protected FieldInfo m_DataField = null;
  50. public MSSQLGenericTableHandler(string connectionString,
  51. string realm, string storeName)
  52. {
  53. m_Realm = realm;
  54. m_ConnectionString = connectionString;
  55. if (storeName != String.Empty)
  56. {
  57. using (SqlConnection conn = new SqlConnection(m_ConnectionString))
  58. {
  59. conn.Open();
  60. Migration m = new Migration(conn, GetType().Assembly, storeName);
  61. m.Update();
  62. }
  63. }
  64. m_database = new MSSQLManager(m_ConnectionString);
  65. Type t = typeof(T);
  66. FieldInfo[] fields = t.GetFields(BindingFlags.Public |
  67. BindingFlags.Instance |
  68. BindingFlags.DeclaredOnly);
  69. if (fields.Length == 0)
  70. return;
  71. foreach (FieldInfo f in fields)
  72. {
  73. if (f.Name != "Data")
  74. m_Fields[f.Name] = f;
  75. else
  76. m_DataField = f;
  77. }
  78. }
  79. private void CheckColumnNames(SqlDataReader reader)
  80. {
  81. if (m_ColumnNames != null)
  82. return;
  83. m_ColumnNames = new List<string>();
  84. DataTable schemaTable = reader.GetSchemaTable();
  85. foreach (DataRow row in schemaTable.Rows)
  86. {
  87. if (row["ColumnName"] != null &&
  88. (!m_Fields.ContainsKey(row["ColumnName"].ToString())))
  89. m_ColumnNames.Add(row["ColumnName"].ToString());
  90. }
  91. }
  92. private List<string> GetConstraints()
  93. {
  94. List<string> constraints = new List<string>();
  95. string query = string.Format(@"SELECT
  96. COL_NAME(ic.object_id,ic.column_id) AS column_name
  97. FROM sys.indexes AS i
  98. INNER JOIN sys.index_columns AS ic
  99. ON i.object_id = ic.object_id AND i.index_id = ic.index_id
  100. WHERE i.is_primary_key = 1
  101. AND i.object_id = OBJECT_ID('{0}');", m_Realm);
  102. using (SqlConnection conn = new SqlConnection(m_ConnectionString))
  103. using (SqlCommand cmd = new SqlCommand(query, conn))
  104. {
  105. conn.Open();
  106. using (SqlDataReader rdr = cmd.ExecuteReader())
  107. {
  108. while (rdr.Read())
  109. {
  110. // query produces 0 to many rows of single column, so always add the first item in each row
  111. constraints.Add((string)rdr[0]);
  112. }
  113. }
  114. return constraints;
  115. }
  116. }
  117. public virtual T[] Get(string field, string key)
  118. {
  119. return Get(new string[] { field }, new string[] { key });
  120. }
  121. public virtual T[] Get(string[] fields, string[] keys)
  122. {
  123. if (fields.Length != keys.Length)
  124. return new T[0];
  125. List<string> terms = new List<string>();
  126. using (SqlConnection conn = new SqlConnection(m_ConnectionString))
  127. using (SqlCommand cmd = new SqlCommand())
  128. {
  129. for (int i = 0; i < fields.Length; i++)
  130. {
  131. cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i]));
  132. terms.Add("[" + fields[i] + "] = @" + fields[i]);
  133. }
  134. string where = String.Join(" AND ", terms.ToArray());
  135. string query = String.Format("SELECT * FROM {0} WHERE {1}",
  136. m_Realm, where);
  137. cmd.Connection = conn;
  138. cmd.CommandText = query;
  139. conn.Open();
  140. return DoQuery(cmd);
  141. }
  142. }
  143. protected T[] DoQuery(SqlCommand cmd)
  144. {
  145. List<T> result = new List<T>();
  146. using (SqlDataReader reader = cmd.ExecuteReader())
  147. {
  148. if (reader == null)
  149. return new T[0];
  150. CheckColumnNames(reader);
  151. while (reader.Read())
  152. {
  153. T row = new T();
  154. foreach (string name in m_Fields.Keys)
  155. {
  156. if (m_Fields[name].GetValue(row) is bool)
  157. {
  158. int v = Convert.ToInt32(reader[name]);
  159. m_Fields[name].SetValue(row, v != 0 ? true : false);
  160. }
  161. else if (m_Fields[name].GetValue(row) is UUID)
  162. {
  163. UUID uuid = UUID.Zero;
  164. UUID.TryParse(reader[name].ToString(), out uuid);
  165. m_Fields[name].SetValue(row, uuid);
  166. }
  167. else if (m_Fields[name].GetValue(row) is int)
  168. {
  169. int v = Convert.ToInt32(reader[name]);
  170. m_Fields[name].SetValue(row, v);
  171. }
  172. else
  173. {
  174. m_Fields[name].SetValue(row, reader[name]);
  175. }
  176. }
  177. if (m_DataField != null)
  178. {
  179. Dictionary<string, string> data =
  180. new Dictionary<string, string>();
  181. foreach (string col in m_ColumnNames)
  182. {
  183. data[col] = reader[col].ToString();
  184. if (data[col] == null)
  185. data[col] = String.Empty;
  186. }
  187. m_DataField.SetValue(row, data);
  188. }
  189. result.Add(row);
  190. }
  191. return result.ToArray();
  192. }
  193. }
  194. public virtual T[] Get(string where)
  195. {
  196. using (SqlConnection conn = new SqlConnection(m_ConnectionString))
  197. using (SqlCommand cmd = new SqlCommand())
  198. {
  199. string query = String.Format("SELECT * FROM {0} WHERE {1}",
  200. m_Realm, where);
  201. cmd.Connection = conn;
  202. cmd.CommandText = query;
  203. //m_log.WarnFormat("[MSSQLGenericTable]: SELECT {0} WHERE {1}", m_Realm, where);
  204. conn.Open();
  205. return DoQuery(cmd);
  206. }
  207. }
  208. public virtual bool Store(T row)
  209. {
  210. List<string> constraintFields = GetConstraints();
  211. List<KeyValuePair<string, string>> constraints = new List<KeyValuePair<string, string>>();
  212. using (SqlConnection conn = new SqlConnection(m_ConnectionString))
  213. using (SqlCommand cmd = new SqlCommand())
  214. {
  215. StringBuilder query = new StringBuilder();
  216. List<String> names = new List<String>();
  217. List<String> values = new List<String>();
  218. foreach (FieldInfo fi in m_Fields.Values)
  219. {
  220. names.Add(fi.Name);
  221. values.Add("@" + fi.Name);
  222. // Temporarily return more information about what field is unexpectedly null for
  223. // http://opensimulator.org/mantis/view.php?id=5403. This might be due to a bug in the
  224. // InventoryTransferModule or we may be required to substitute a DBNull here.
  225. if (fi.GetValue(row) == null)
  226. throw new NullReferenceException(
  227. string.Format(
  228. "[MSSQL GENERIC TABLE HANDLER]: Trying to store field {0} for {1} which is unexpectedly null",
  229. fi.Name, row));
  230. if (constraintFields.Count > 0 && constraintFields.Contains(fi.Name))
  231. {
  232. constraints.Add(new KeyValuePair<string, string>(fi.Name, fi.GetValue(row).ToString()));
  233. }
  234. cmd.Parameters.Add(m_database.CreateParameter(fi.Name, fi.GetValue(row).ToString()));
  235. }
  236. if (m_DataField != null)
  237. {
  238. Dictionary<string, string> data =
  239. (Dictionary<string, string>)m_DataField.GetValue(row);
  240. foreach (KeyValuePair<string, string> kvp in data)
  241. {
  242. if (constraintFields.Count > 0 && constraintFields.Contains(kvp.Key))
  243. {
  244. constraints.Add(new KeyValuePair<string, string>(kvp.Key, kvp.Key));
  245. }
  246. names.Add(kvp.Key);
  247. values.Add("@" + kvp.Key);
  248. cmd.Parameters.Add(m_database.CreateParameter("@" + kvp.Key, kvp.Value));
  249. }
  250. }
  251. query.AppendFormat("UPDATE {0} SET ", m_Realm);
  252. int i = 0;
  253. for (i = 0; i < names.Count - 1; i++)
  254. {
  255. query.AppendFormat("[{0}] = {1}, ", names[i], values[i]);
  256. }
  257. query.AppendFormat("[{0}] = {1} ", names[i], values[i]);
  258. if (constraints.Count > 0)
  259. {
  260. List<string> terms = new List<string>();
  261. for (int j = 0; j < constraints.Count; j++)
  262. {
  263. terms.Add(" [" + constraints[j].Key + "] = @" + constraints[j].Key);
  264. }
  265. string where = String.Join(" AND ", terms.ToArray());
  266. query.AppendFormat(" WHERE {0} ", where);
  267. }
  268. cmd.Connection = conn;
  269. cmd.CommandText = query.ToString();
  270. conn.Open();
  271. if (cmd.ExecuteNonQuery() > 0)
  272. {
  273. //m_log.WarnFormat("[MSSQLGenericTable]: Updating {0}", m_Realm);
  274. return true;
  275. }
  276. else
  277. {
  278. // assume record has not yet been inserted
  279. query = new StringBuilder();
  280. query.AppendFormat("INSERT INTO {0} ([", m_Realm);
  281. query.Append(String.Join("],[", names.ToArray()));
  282. query.Append("]) values (" + String.Join(",", values.ToArray()) + ")");
  283. cmd.Connection = conn;
  284. cmd.CommandText = query.ToString();
  285. //m_log.WarnFormat("[MSSQLGenericTable]: Inserting into {0}", m_Realm);
  286. if (conn.State != ConnectionState.Open)
  287. conn.Open();
  288. if (cmd.ExecuteNonQuery() > 0)
  289. return true;
  290. }
  291. return false;
  292. }
  293. }
  294. public virtual bool Delete(string field, string key)
  295. {
  296. return Delete(new string[] { field }, new string[] { key });
  297. }
  298. public virtual bool Delete(string[] fields, string[] keys)
  299. {
  300. if (fields.Length != keys.Length)
  301. return false;
  302. List<string> terms = new List<string>();
  303. using (SqlConnection conn = new SqlConnection(m_ConnectionString))
  304. using (SqlCommand cmd = new SqlCommand())
  305. {
  306. for (int i = 0; i < fields.Length; i++)
  307. {
  308. cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i]));
  309. terms.Add("[" + fields[i] + "] = @" + fields[i]);
  310. }
  311. string where = String.Join(" AND ", terms.ToArray());
  312. string query = String.Format("DELETE FROM {0} WHERE {1}", m_Realm, where);
  313. cmd.Connection = conn;
  314. cmd.CommandText = query;
  315. conn.Open();
  316. if (cmd.ExecuteNonQuery() > 0)
  317. {
  318. //m_log.Warn("[MSSQLGenericTable]: " + deleteCommand);
  319. return true;
  320. }
  321. return false;
  322. }
  323. }
  324. }
  325. }