MySQLGenericTableHandler.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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 MySql.Data.MySqlClient;
  33. using OpenMetaverse;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.Framework.Interfaces;
  36. namespace OpenSim.Data.MySQL
  37. {
  38. public class MySQLGenericTableHandler<T> : MySqlFramework where T: class, new()
  39. {
  40. // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  41. protected Dictionary<string, FieldInfo> m_Fields =
  42. new Dictionary<string, FieldInfo>();
  43. protected List<string> m_ColumnNames = null;
  44. protected string m_Realm;
  45. protected FieldInfo m_DataField = null;
  46. protected virtual Assembly Assembly
  47. {
  48. get { return GetType().Assembly; }
  49. }
  50. public MySQLGenericTableHandler(MySqlTransaction trans,
  51. string realm, string storeName) : base(trans)
  52. {
  53. m_Realm = realm;
  54. CommonConstruct(storeName);
  55. }
  56. public MySQLGenericTableHandler(string connectionString,
  57. string realm, string storeName) : base(connectionString)
  58. {
  59. m_Realm = realm;
  60. CommonConstruct(storeName);
  61. }
  62. protected void CommonConstruct(string storeName)
  63. {
  64. if (storeName != String.Empty)
  65. {
  66. // We always use a new connection for any Migrations
  67. using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
  68. {
  69. dbcon.Open();
  70. Migration m = new Migration(dbcon, Assembly, storeName);
  71. m.Update();
  72. }
  73. }
  74. Type t = typeof(T);
  75. FieldInfo[] fields = t.GetFields(BindingFlags.Public |
  76. BindingFlags.Instance |
  77. BindingFlags.DeclaredOnly);
  78. if (fields.Length == 0)
  79. return;
  80. foreach (FieldInfo f in fields)
  81. {
  82. if (f.Name != "Data")
  83. m_Fields[f.Name] = f;
  84. else
  85. m_DataField = f;
  86. }
  87. }
  88. private void CheckColumnNames(IDataReader reader)
  89. {
  90. if (m_ColumnNames != null)
  91. return;
  92. List<string> columnNames = new List<string>();
  93. DataTable schemaTable = reader.GetSchemaTable();
  94. foreach (DataRow row in schemaTable.Rows)
  95. {
  96. if (row["ColumnName"] != null &&
  97. (!m_Fields.ContainsKey(row["ColumnName"].ToString())))
  98. columnNames.Add(row["ColumnName"].ToString());
  99. }
  100. m_ColumnNames = columnNames;
  101. }
  102. public virtual T[] Get(string field, string key)
  103. {
  104. return Get(new string[] { field }, new string[] { key });
  105. }
  106. public virtual T[] Get(string[] fields, string[] keys)
  107. {
  108. return Get(fields, keys, String.Empty);
  109. }
  110. public virtual T[] Get(string[] fields, string[] keys, string options)
  111. {
  112. if (fields.Length != keys.Length)
  113. return new T[0];
  114. List<string> terms = new List<string>();
  115. using (MySqlCommand cmd = new MySqlCommand())
  116. {
  117. for (int i = 0 ; i < fields.Length ; i++)
  118. {
  119. cmd.Parameters.AddWithValue(fields[i], keys[i]);
  120. terms.Add("`" + fields[i] + "` = ?" + fields[i]);
  121. }
  122. string where = String.Join(" and ", terms.ToArray());
  123. string query = String.Format("select * from {0} where {1} {2}",
  124. m_Realm, where, options);
  125. cmd.CommandText = query;
  126. return DoQuery(cmd);
  127. }
  128. }
  129. protected T[] DoQuery(MySqlCommand cmd)
  130. {
  131. if (m_trans == null)
  132. {
  133. using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
  134. {
  135. dbcon.Open();
  136. T[] ret = DoQueryWithConnection(cmd, dbcon);
  137. dbcon.Close();
  138. return ret;
  139. }
  140. }
  141. else
  142. {
  143. return DoQueryWithTransaction(cmd, m_trans);
  144. }
  145. }
  146. protected T[] DoQueryWithTransaction(MySqlCommand cmd, MySqlTransaction trans)
  147. {
  148. cmd.Transaction = trans;
  149. return DoQueryWithConnection(cmd, trans.Connection);
  150. }
  151. protected T[] DoQueryWithConnection(MySqlCommand cmd, MySqlConnection dbcon)
  152. {
  153. List<T> result = new List<T>();
  154. cmd.Connection = dbcon;
  155. using (IDataReader reader = cmd.ExecuteReader())
  156. {
  157. if (reader == null)
  158. return new T[0];
  159. CheckColumnNames(reader);
  160. while (reader.Read())
  161. {
  162. T row = new T();
  163. foreach (string name in m_Fields.Keys)
  164. {
  165. if (reader[name] is DBNull)
  166. {
  167. continue;
  168. }
  169. if (m_Fields[name].FieldType == typeof(bool))
  170. {
  171. int v = Convert.ToInt32(reader[name]);
  172. m_Fields[name].SetValue(row, v != 0 ? true : false);
  173. }
  174. else if (m_Fields[name].FieldType == typeof(UUID))
  175. {
  176. m_Fields[name].SetValue(row, DBGuid.FromDB(reader[name]));
  177. }
  178. else if (m_Fields[name].FieldType == typeof(int))
  179. {
  180. int v = Convert.ToInt32(reader[name]);
  181. m_Fields[name].SetValue(row, v);
  182. }
  183. else if (m_Fields[name].FieldType == typeof(uint))
  184. {
  185. uint v = Convert.ToUInt32(reader[name]);
  186. m_Fields[name].SetValue(row, v);
  187. }
  188. else
  189. {
  190. m_Fields[name].SetValue(row, reader[name]);
  191. }
  192. }
  193. if (m_DataField != null)
  194. {
  195. Dictionary<string, string> data =
  196. new Dictionary<string, string>();
  197. foreach (string col in m_ColumnNames)
  198. {
  199. data[col] = reader[col].ToString();
  200. if (data[col] == null)
  201. data[col] = String.Empty;
  202. }
  203. m_DataField.SetValue(row, data);
  204. }
  205. result.Add(row);
  206. }
  207. }
  208. cmd.Connection = null;
  209. return result.ToArray();
  210. }
  211. public virtual T[] Get(string where)
  212. {
  213. using (MySqlCommand cmd = new MySqlCommand())
  214. {
  215. string query = String.Format("select * from {0} where {1}",
  216. m_Realm, where);
  217. cmd.CommandText = query;
  218. return DoQuery(cmd);
  219. }
  220. }
  221. public virtual bool Store(T row)
  222. {
  223. // m_log.DebugFormat("[MYSQL GENERIC TABLE HANDLER]: Store(T row) invoked");
  224. using (MySqlCommand cmd = new MySqlCommand())
  225. {
  226. string query = "";
  227. List<String> names = new List<String>();
  228. List<String> values = new List<String>();
  229. foreach (FieldInfo fi in m_Fields.Values)
  230. {
  231. names.Add(fi.Name);
  232. values.Add("?" + fi.Name);
  233. // Temporarily return more information about what field is unexpectedly null for
  234. // http://opensimulator.org/mantis/view.php?id=5403. This might be due to a bug in the
  235. // InventoryTransferModule or we may be required to substitute a DBNull here.
  236. if (fi.GetValue(row) == null)
  237. throw new NullReferenceException(
  238. string.Format(
  239. "[MYSQL GENERIC TABLE HANDLER]: Trying to store field {0} for {1} which is unexpectedly null",
  240. fi.Name, row));
  241. cmd.Parameters.AddWithValue(fi.Name, fi.GetValue(row).ToString());
  242. }
  243. if (m_DataField != null)
  244. {
  245. Dictionary<string, string> data =
  246. (Dictionary<string, string>)m_DataField.GetValue(row);
  247. foreach (KeyValuePair<string, string> kvp in data)
  248. {
  249. names.Add(kvp.Key);
  250. values.Add("?" + kvp.Key);
  251. cmd.Parameters.AddWithValue("?" + kvp.Key, kvp.Value);
  252. }
  253. }
  254. query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values (" + String.Join(",", values.ToArray()) + ")";
  255. cmd.CommandText = query;
  256. if (ExecuteNonQuery(cmd) > 0)
  257. return true;
  258. return false;
  259. }
  260. }
  261. public virtual bool Delete(string field, string key)
  262. {
  263. return Delete(new string[] { field }, new string[] { key });
  264. }
  265. public virtual bool Delete(string[] fields, string[] keys)
  266. {
  267. // m_log.DebugFormat(
  268. // "[MYSQL GENERIC TABLE HANDLER]: Delete(string[] fields, string[] keys) invoked with {0}:{1}",
  269. // string.Join(",", fields), string.Join(",", keys));
  270. if (fields.Length != keys.Length)
  271. return false;
  272. List<string> terms = new List<string>();
  273. using (MySqlCommand cmd = new MySqlCommand())
  274. {
  275. for (int i = 0 ; i < fields.Length ; i++)
  276. {
  277. cmd.Parameters.AddWithValue(fields[i], keys[i]);
  278. terms.Add("`" + fields[i] + "` = ?" + fields[i]);
  279. }
  280. string where = String.Join(" and ", terms.ToArray());
  281. string query = String.Format("delete from {0} where {1}", m_Realm, where);
  282. cmd.CommandText = query;
  283. return ExecuteNonQuery(cmd) > 0;
  284. }
  285. }
  286. public long GetCount(string field, string key)
  287. {
  288. return GetCount(new string[] { field }, new string[] { key });
  289. }
  290. public long GetCount(string[] fields, string[] keys)
  291. {
  292. if (fields.Length != keys.Length)
  293. return 0;
  294. List<string> terms = new List<string>();
  295. using (MySqlCommand cmd = new MySqlCommand())
  296. {
  297. for (int i = 0; i < fields.Length; i++)
  298. {
  299. cmd.Parameters.AddWithValue(fields[i], keys[i]);
  300. terms.Add("`" + fields[i] + "` = ?" + fields[i]);
  301. }
  302. string where = String.Join(" and ", terms.ToArray());
  303. string query = String.Format("select count(*) from {0} where {1}",
  304. m_Realm, where);
  305. cmd.CommandText = query;
  306. Object result = DoQueryScalar(cmd);
  307. return Convert.ToInt64(result);
  308. }
  309. }
  310. public long GetCount(string where)
  311. {
  312. using (MySqlCommand cmd = new MySqlCommand())
  313. {
  314. string query = String.Format("select count(*) from {0} where {1}",
  315. m_Realm, where);
  316. cmd.CommandText = query;
  317. object result = DoQueryScalar(cmd);
  318. return Convert.ToInt64(result);
  319. }
  320. }
  321. public object DoQueryScalar(MySqlCommand cmd)
  322. {
  323. if (m_trans == null)
  324. {
  325. using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
  326. {
  327. dbcon.Open();
  328. cmd.Connection = dbcon;
  329. Object ret = cmd.ExecuteScalar();
  330. cmd.Connection = null;
  331. dbcon.Close();
  332. return ret;
  333. }
  334. }
  335. else
  336. {
  337. cmd.Connection = m_trans.Connection;
  338. cmd.Transaction = m_trans;
  339. return cmd.ExecuteScalar();
  340. }
  341. }
  342. }
  343. }