MySQLGenericTableHandler.cs 15 KB

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