MSSQLGenericTableHandler.cs 14 KB

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