1
0

SQLiteGenericTableHandler.cs 9.9 KB

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