1
0

MySQLGenericTableHandler.cs 16 KB

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