SQLiteGenericTableHandler.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. #if CSharpSqlite
  33. using Community.CsharpSqlite.Sqlite;
  34. #else
  35. using Mono.Data.Sqlite;
  36. #endif
  37. using OpenMetaverse;
  38. using OpenSim.Framework;
  39. using OpenSim.Region.Framework.Interfaces;
  40. namespace OpenSim.Data.SQLite
  41. {
  42. public class SQLiteGenericTableHandler<T> : SQLiteFramework where T: class, new()
  43. {
  44. // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  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. protected static SqliteConnection m_Connection;
  51. private static bool m_initialized;
  52. public SQLiteGenericTableHandler(string connectionString,
  53. string realm, string storeName) : base(connectionString)
  54. {
  55. m_Realm = realm;
  56. if (!m_initialized)
  57. {
  58. m_Connection = new SqliteConnection(connectionString);
  59. //Console.WriteLine(string.Format("OPENING CONNECTION FOR {0} USING {1}", storeName, connectionString));
  60. m_Connection.Open();
  61. if (storeName != String.Empty)
  62. {
  63. Assembly assem = GetType().Assembly;
  64. //SqliteConnection newConnection =
  65. // (SqliteConnection)((ICloneable)m_Connection).Clone();
  66. //newConnection.Open();
  67. //Migration m = new Migration(newConnection, assem, storeName);
  68. Migration m = new Migration(m_Connection, assem, storeName);
  69. m.Update();
  70. //newConnection.Close();
  71. //newConnection.Dispose();
  72. }
  73. m_initialized = true;
  74. }
  75. Type t = typeof(T);
  76. FieldInfo[] fields = t.GetFields(BindingFlags.Public |
  77. BindingFlags.Instance |
  78. BindingFlags.DeclaredOnly);
  79. if (fields.Length == 0)
  80. return;
  81. foreach (FieldInfo f in fields)
  82. {
  83. if (f.Name != "Data")
  84. m_Fields[f.Name] = f;
  85. else
  86. m_DataField = f;
  87. }
  88. }
  89. private void CheckColumnNames(IDataReader reader)
  90. {
  91. if (m_ColumnNames != null)
  92. return;
  93. m_ColumnNames = new List<string>();
  94. DataTable schemaTable = reader.GetSchemaTable();
  95. foreach (DataRow row in schemaTable.Rows)
  96. {
  97. if (row["ColumnName"] != null &&
  98. (!m_Fields.ContainsKey(row["ColumnName"].ToString())))
  99. m_ColumnNames.Add(row["ColumnName"].ToString());
  100. }
  101. }
  102. public T[] Get(string field, string key)
  103. {
  104. return Get(new string[] { field }, new string[] { key });
  105. }
  106. public T[] Get(string[] fields, string[] keys)
  107. {
  108. if (fields.Length != keys.Length)
  109. return new T[0];
  110. List<string> terms = new List<string>();
  111. SqliteCommand cmd = new SqliteCommand();
  112. for (int i = 0 ; i < fields.Length ; i++)
  113. {
  114. cmd.Parameters.Add(new SqliteParameter(":" + fields[i], keys[i]));
  115. terms.Add("`" + fields[i] + "` = :" + fields[i]);
  116. }
  117. string where = String.Join(" and ", terms.ToArray());
  118. string query = String.Format("select * from {0} where {1}",
  119. m_Realm, where);
  120. cmd.CommandText = query;
  121. return DoQuery(cmd);
  122. }
  123. protected T[] DoQuery(SqliteCommand cmd)
  124. {
  125. IDataReader reader = ExecuteReader(cmd, m_Connection);
  126. if (reader == null)
  127. return new T[0];
  128. CheckColumnNames(reader);
  129. List<T> result = new List<T>();
  130. while (reader.Read())
  131. {
  132. T row = new T();
  133. foreach (string name in m_Fields.Keys)
  134. {
  135. if (m_Fields[name].GetValue(row) is bool)
  136. {
  137. int v = Convert.ToInt32(reader[name]);
  138. m_Fields[name].SetValue(row, v != 0 ? true : false);
  139. }
  140. else if (m_Fields[name].GetValue(row) is UUID)
  141. {
  142. UUID uuid = UUID.Zero;
  143. UUID.TryParse(reader[name].ToString(), out uuid);
  144. m_Fields[name].SetValue(row, uuid);
  145. }
  146. else if (m_Fields[name].GetValue(row) is int)
  147. {
  148. int v = Convert.ToInt32(reader[name]);
  149. m_Fields[name].SetValue(row, v);
  150. }
  151. else
  152. {
  153. m_Fields[name].SetValue(row, reader[name]);
  154. }
  155. }
  156. if (m_DataField != null)
  157. {
  158. Dictionary<string, string> data =
  159. new Dictionary<string, string>();
  160. foreach (string col in m_ColumnNames)
  161. {
  162. data[col] = reader[col].ToString();
  163. if (data[col] == null)
  164. data[col] = String.Empty;
  165. }
  166. m_DataField.SetValue(row, data);
  167. }
  168. result.Add(row);
  169. }
  170. //CloseCommand(cmd);
  171. return result.ToArray();
  172. }
  173. public T[] Get(string where)
  174. {
  175. SqliteCommand cmd = new SqliteCommand();
  176. string query = String.Format("select * from {0} where {1}",
  177. m_Realm, where);
  178. cmd.CommandText = query;
  179. return DoQuery(cmd);
  180. }
  181. public bool Store(T row)
  182. {
  183. SqliteCommand cmd = new SqliteCommand();
  184. string query = "";
  185. List<String> names = new List<String>();
  186. List<String> values = new List<String>();
  187. foreach (FieldInfo fi in m_Fields.Values)
  188. {
  189. names.Add(fi.Name);
  190. values.Add(":" + fi.Name);
  191. cmd.Parameters.Add(new SqliteParameter(":" + fi.Name, fi.GetValue(row).ToString()));
  192. }
  193. if (m_DataField != null)
  194. {
  195. Dictionary<string, string> data =
  196. (Dictionary<string, string>)m_DataField.GetValue(row);
  197. foreach (KeyValuePair<string, string> kvp in data)
  198. {
  199. names.Add(kvp.Key);
  200. values.Add(":" + kvp.Key);
  201. cmd.Parameters.Add(new SqliteParameter(":" + kvp.Key, kvp.Value));
  202. }
  203. }
  204. query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values (" + String.Join(",", values.ToArray()) + ")";
  205. cmd.CommandText = query;
  206. if (ExecuteNonQuery(cmd, m_Connection) > 0)
  207. return true;
  208. return false;
  209. }
  210. public virtual bool Delete(string field, string key)
  211. {
  212. return Delete(new string[] { field }, new string[] { key });
  213. }
  214. public bool Delete(string[] fields, string[] keys)
  215. {
  216. if (fields.Length != keys.Length)
  217. return false;
  218. List<string> terms = new List<string>();
  219. SqliteCommand cmd = new SqliteCommand();
  220. for (int i = 0 ; i < fields.Length ; i++)
  221. {
  222. cmd.Parameters.Add(new SqliteParameter(":" + fields[i], keys[i]));
  223. terms.Add("`" + fields[i] + "` = :" + fields[i]);
  224. }
  225. string where = String.Join(" and ", terms.ToArray());
  226. string query = String.Format("delete from {0} where {1}", m_Realm, where);
  227. cmd.CommandText = query;
  228. return ExecuteNonQuery(cmd, m_Connection) > 0;
  229. }
  230. }
  231. }