1
0

SQLiteGenericTableHandler.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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 virtual T[] Get(string field, string key)
  106. {
  107. return Get(new string[] { field }, new string[] { key });
  108. }
  109. public virtual 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. using (SqliteCommand cmd = new SqliteCommand())
  115. {
  116. for (int i = 0 ; i < fields.Length ; i++)
  117. {
  118. cmd.Parameters.Add(new SqliteParameter(":" + fields[i], keys[i]));
  119. terms.Add("`" + fields[i] + "` = :" + fields[i]);
  120. }
  121. string where = String.Join(" and ", terms.ToArray());
  122. string query = String.Format("select * from {0} where {1}",
  123. m_Realm, where);
  124. cmd.CommandText = query;
  125. return DoQuery(cmd);
  126. }
  127. }
  128. protected T[] DoQuery(SqliteCommand cmd)
  129. {
  130. IDataReader reader = ExecuteReader(cmd, m_Connection);
  131. if (reader == null)
  132. return new T[0];
  133. CheckColumnNames(reader);
  134. List<T> result = new List<T>();
  135. while (reader.Read())
  136. {
  137. T row = new T();
  138. foreach (string name in m_Fields.Keys)
  139. {
  140. if (m_Fields[name].GetValue(row) is bool)
  141. {
  142. int v = Convert.ToInt32(reader[name]);
  143. m_Fields[name].SetValue(row, v != 0 ? true : false);
  144. }
  145. else if (m_Fields[name].GetValue(row) is UUID)
  146. {
  147. UUID uuid = UUID.Zero;
  148. UUID.TryParse(reader[name].ToString(), out uuid);
  149. m_Fields[name].SetValue(row, uuid);
  150. }
  151. else if (m_Fields[name].GetValue(row) is int)
  152. {
  153. int v = Convert.ToInt32(reader[name]);
  154. m_Fields[name].SetValue(row, v);
  155. }
  156. else
  157. {
  158. m_Fields[name].SetValue(row, reader[name]);
  159. }
  160. }
  161. if (m_DataField != null)
  162. {
  163. Dictionary<string, string> data =
  164. new Dictionary<string, string>();
  165. foreach (string col in m_ColumnNames)
  166. {
  167. data[col] = reader[col].ToString();
  168. if (data[col] == null)
  169. data[col] = String.Empty;
  170. }
  171. m_DataField.SetValue(row, data);
  172. }
  173. result.Add(row);
  174. }
  175. //CloseCommand(cmd);
  176. return result.ToArray();
  177. }
  178. public virtual T[] Get(string where)
  179. {
  180. using (SqliteCommand cmd = new SqliteCommand())
  181. {
  182. string query = String.Format("select * from {0} where {1}",
  183. m_Realm, where);
  184. cmd.CommandText = query;
  185. return DoQuery(cmd);
  186. }
  187. }
  188. public virtual bool Store(T row)
  189. {
  190. using (SqliteCommand cmd = new SqliteCommand())
  191. {
  192. string query = "";
  193. List<String> names = new List<String>();
  194. List<String> values = new List<String>();
  195. foreach (FieldInfo fi in m_Fields.Values)
  196. {
  197. names.Add(fi.Name);
  198. values.Add(":" + fi.Name);
  199. cmd.Parameters.Add(new SqliteParameter(":" + fi.Name, fi.GetValue(row).ToString()));
  200. }
  201. if (m_DataField != null)
  202. {
  203. Dictionary<string, string> data =
  204. (Dictionary<string, string>)m_DataField.GetValue(row);
  205. foreach (KeyValuePair<string, string> kvp in data)
  206. {
  207. names.Add(kvp.Key);
  208. values.Add(":" + kvp.Key);
  209. cmd.Parameters.Add(new SqliteParameter(":" + kvp.Key, kvp.Value));
  210. }
  211. }
  212. query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values (" + String.Join(",", values.ToArray()) + ")";
  213. cmd.CommandText = query;
  214. if (ExecuteNonQuery(cmd, m_Connection) > 0)
  215. return true;
  216. }
  217. return false;
  218. }
  219. public virtual bool Delete(string field, string key)
  220. {
  221. return Delete(new string[] { field }, new string[] { key });
  222. }
  223. public virtual bool Delete(string[] fields, string[] keys)
  224. {
  225. if (fields.Length != keys.Length)
  226. return false;
  227. List<string> terms = new List<string>();
  228. using (SqliteCommand cmd = new SqliteCommand())
  229. {
  230. for (int i = 0 ; i < fields.Length ; i++)
  231. {
  232. cmd.Parameters.Add(new SqliteParameter(":" + fields[i], keys[i]));
  233. terms.Add("`" + fields[i] + "` = :" + fields[i]);
  234. }
  235. string where = String.Join(" and ", terms.ToArray());
  236. string query = String.Format("delete from {0} where {1}", m_Realm, where);
  237. cmd.CommandText = query;
  238. return ExecuteNonQuery(cmd, m_Connection) > 0;
  239. }
  240. }
  241. }
  242. }