SQLiteGenericTableHandler.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 Mono.Data.Sqlite;
  33. using OpenMetaverse;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.Framework.Interfaces;
  36. namespace OpenSim.Data.SQLite
  37. {
  38. public class SQLiteGenericTableHandler<T> : SQLiteFramework 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 static SqliteConnection m_Connection;
  47. private static bool m_initialized;
  48. public SQLiteGenericTableHandler(string connectionString,
  49. string realm, string storeName) : base(connectionString)
  50. {
  51. m_Realm = realm;
  52. if (!m_initialized)
  53. {
  54. m_Connection = new SqliteConnection(connectionString);
  55. //Console.WriteLine(string.Format("OPENING CONNECTION FOR {0} USING {1}", storeName, connectionString));
  56. m_Connection.Open();
  57. if (storeName != String.Empty)
  58. {
  59. Assembly assem = GetType().Assembly;
  60. //SqliteConnection newConnection =
  61. // (SqliteConnection)((ICloneable)m_Connection).Clone();
  62. //newConnection.Open();
  63. //Migration m = new Migration(newConnection, assem, storeName);
  64. Migration m = new Migration(m_Connection, assem, storeName);
  65. m.Update();
  66. //newConnection.Close();
  67. //newConnection.Dispose();
  68. }
  69. m_initialized = true;
  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. m_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. m_ColumnNames.Add(row["ColumnName"].ToString());
  96. }
  97. }
  98. public T[] Get(string field, string key)
  99. {
  100. return Get(new string[] { field }, new string[] { key });
  101. }
  102. public T[] Get(string[] fields, string[] keys)
  103. {
  104. if (fields.Length != keys.Length)
  105. return new T[0];
  106. List<string> terms = new List<string>();
  107. SqliteCommand cmd = new SqliteCommand();
  108. for (int i = 0 ; i < fields.Length ; i++)
  109. {
  110. cmd.Parameters.Add(new SqliteParameter(":" + fields[i], keys[i]));
  111. terms.Add("`" + fields[i] + "` = :" + fields[i]);
  112. }
  113. string where = String.Join(" and ", terms.ToArray());
  114. string query = String.Format("select * from {0} where {1}",
  115. m_Realm, where);
  116. cmd.CommandText = query;
  117. return DoQuery(cmd);
  118. }
  119. protected T[] DoQuery(SqliteCommand cmd)
  120. {
  121. IDataReader reader = ExecuteReader(cmd, m_Connection);
  122. if (reader == null)
  123. return new T[0];
  124. CheckColumnNames(reader);
  125. List<T> result = new List<T>();
  126. while (reader.Read())
  127. {
  128. T row = new T();
  129. foreach (string name in m_Fields.Keys)
  130. {
  131. if (m_Fields[name].GetValue(row) is bool)
  132. {
  133. int v = Convert.ToInt32(reader[name]);
  134. m_Fields[name].SetValue(row, v != 0 ? true : false);
  135. }
  136. else if (m_Fields[name].GetValue(row) is UUID)
  137. {
  138. UUID uuid = UUID.Zero;
  139. UUID.TryParse(reader[name].ToString(), out uuid);
  140. m_Fields[name].SetValue(row, uuid);
  141. }
  142. else if (m_Fields[name].GetValue(row) is int)
  143. {
  144. int v = Convert.ToInt32(reader[name]);
  145. m_Fields[name].SetValue(row, v);
  146. }
  147. else
  148. {
  149. m_Fields[name].SetValue(row, reader[name]);
  150. }
  151. }
  152. if (m_DataField != null)
  153. {
  154. Dictionary<string, string> data =
  155. new Dictionary<string, string>();
  156. foreach (string col in m_ColumnNames)
  157. {
  158. data[col] = reader[col].ToString();
  159. if (data[col] == null)
  160. data[col] = String.Empty;
  161. }
  162. m_DataField.SetValue(row, data);
  163. }
  164. result.Add(row);
  165. }
  166. //CloseCommand(cmd);
  167. return result.ToArray();
  168. }
  169. public T[] Get(string where)
  170. {
  171. SqliteCommand cmd = new SqliteCommand();
  172. string query = String.Format("select * from {0} where {1}",
  173. m_Realm, where);
  174. cmd.CommandText = query;
  175. return DoQuery(cmd);
  176. }
  177. public bool Store(T row)
  178. {
  179. SqliteCommand cmd = new SqliteCommand();
  180. string query = "";
  181. List<String> names = new List<String>();
  182. List<String> values = new List<String>();
  183. foreach (FieldInfo fi in m_Fields.Values)
  184. {
  185. names.Add(fi.Name);
  186. values.Add(":" + fi.Name);
  187. cmd.Parameters.Add(new SqliteParameter(":" + fi.Name, fi.GetValue(row).ToString()));
  188. }
  189. if (m_DataField != null)
  190. {
  191. Dictionary<string, string> data =
  192. (Dictionary<string, string>)m_DataField.GetValue(row);
  193. foreach (KeyValuePair<string, string> kvp in data)
  194. {
  195. names.Add(kvp.Key);
  196. values.Add(":" + kvp.Key);
  197. cmd.Parameters.Add(new SqliteParameter(":" + kvp.Key, kvp.Value));
  198. }
  199. }
  200. query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values (" + String.Join(",", values.ToArray()) + ")";
  201. cmd.CommandText = query;
  202. if (ExecuteNonQuery(cmd, m_Connection) > 0)
  203. return true;
  204. return false;
  205. }
  206. public bool Delete(string field, string val)
  207. {
  208. SqliteCommand cmd = new SqliteCommand();
  209. cmd.CommandText = String.Format("delete from {0} where `{1}` = :{1}", m_Realm, field);
  210. cmd.Parameters.Add(new SqliteParameter(field, val));
  211. if (ExecuteNonQuery(cmd, m_Connection) > 0)
  212. return true;
  213. return false;
  214. }
  215. }
  216. }