PGSQLGenericTableHandler.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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 OpenMetaverse;
  33. using OpenSim.Framework;
  34. using OpenSim.Region.Framework.Interfaces;
  35. using System.Text;
  36. using Npgsql;
  37. namespace OpenSim.Data.PGSQL
  38. {
  39. public class PGSQLGenericTableHandler<T> : PGSqlFramework where T : class, new()
  40. {
  41. private static readonly ILog m_log =
  42. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  43. protected string m_ConnectionString;
  44. protected PGSQLManager m_database; //used for parameter type translation
  45. protected Dictionary<string, FieldInfo> m_Fields =
  46. new Dictionary<string, FieldInfo>();
  47. protected Dictionary<string, string> m_FieldTypes = new Dictionary<string, string>();
  48. protected List<string> m_ColumnNames = null;
  49. protected string m_Realm;
  50. protected FieldInfo m_DataField = null;
  51. protected virtual Assembly Assembly
  52. {
  53. get { return GetType().Assembly; }
  54. }
  55. public PGSQLGenericTableHandler(string connectionString,
  56. string realm, string storeName)
  57. : base(connectionString)
  58. {
  59. m_Realm = realm;
  60. m_ConnectionString = connectionString;
  61. if (storeName != String.Empty)
  62. {
  63. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  64. {
  65. conn.Open();
  66. Migration m = new Migration(conn, GetType().Assembly, storeName);
  67. m.Update();
  68. }
  69. }
  70. m_database = new PGSQLManager(m_ConnectionString);
  71. Type t = typeof(T);
  72. FieldInfo[] fields = t.GetFields(BindingFlags.Public |
  73. BindingFlags.Instance |
  74. BindingFlags.DeclaredOnly);
  75. LoadFieldTypes();
  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 LoadFieldTypes()
  87. {
  88. m_FieldTypes = new Dictionary<string, string>();
  89. string query = string.Format(@"select column_name,data_type
  90. from INFORMATION_SCHEMA.COLUMNS
  91. where table_name = lower('{0}');
  92. ", m_Realm);
  93. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  94. using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn))
  95. {
  96. conn.Open();
  97. using (NpgsqlDataReader rdr = cmd.ExecuteReader())
  98. {
  99. while (rdr.Read())
  100. {
  101. // query produces 0 to many rows of single column, so always add the first item in each row
  102. m_FieldTypes.Add((string)rdr[0], (string)rdr[1]);
  103. }
  104. }
  105. }
  106. }
  107. private void CheckColumnNames(NpgsqlDataReader reader)
  108. {
  109. if (m_ColumnNames != null)
  110. return;
  111. m_ColumnNames = new List<string>();
  112. DataTable schemaTable = reader.GetSchemaTable();
  113. foreach (DataRow row in schemaTable.Rows)
  114. {
  115. if (row["ColumnName"] != null &&
  116. (!m_Fields.ContainsKey(row["ColumnName"].ToString())))
  117. m_ColumnNames.Add(row["ColumnName"].ToString());
  118. }
  119. }
  120. // TODO GET CONSTRAINTS FROM POSTGRESQL
  121. private List<string> GetConstraints()
  122. {
  123. List<string> constraints = new List<string>();
  124. string query = string.Format(@"SELECT kcu.column_name
  125. FROM information_schema.table_constraints tc
  126. LEFT JOIN information_schema.key_column_usage kcu
  127. ON tc.constraint_catalog = kcu.constraint_catalog
  128. AND tc.constraint_schema = kcu.constraint_schema
  129. AND tc.constraint_name = kcu.constraint_name
  130. LEFT JOIN information_schema.referential_constraints rc
  131. ON tc.constraint_catalog = rc.constraint_catalog
  132. AND tc.constraint_schema = rc.constraint_schema
  133. AND tc.constraint_name = rc.constraint_name
  134. LEFT JOIN information_schema.constraint_column_usage ccu
  135. ON rc.unique_constraint_catalog = ccu.constraint_catalog
  136. AND rc.unique_constraint_schema = ccu.constraint_schema
  137. AND rc.unique_constraint_name = ccu.constraint_name
  138. where tc.table_name = lower('{0}')
  139. and lower(tc.constraint_type) in ('primary key')
  140. and kcu.column_name is not null
  141. ;", m_Realm);
  142. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  143. using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn))
  144. {
  145. conn.Open();
  146. using (NpgsqlDataReader rdr = cmd.ExecuteReader())
  147. {
  148. while (rdr.Read())
  149. {
  150. // query produces 0 to many rows of single column, so always add the first item in each row
  151. constraints.Add((string)rdr[0]);
  152. }
  153. }
  154. return constraints;
  155. }
  156. }
  157. public virtual T[] Get(string field, string key)
  158. {
  159. return Get(new string[] { field }, new string[] { key });
  160. }
  161. public virtual T[] Get(string[] fields, string[] keys)
  162. {
  163. if (fields.Length != keys.Length)
  164. return new T[0];
  165. List<string> terms = new List<string>();
  166. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  167. using (NpgsqlCommand cmd = new NpgsqlCommand())
  168. {
  169. for (int i = 0; i < fields.Length; i++)
  170. {
  171. if ( m_FieldTypes.ContainsKey(fields[i]) )
  172. cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i], m_FieldTypes[fields[i]]));
  173. else
  174. cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i]));
  175. terms.Add(" \"" + fields[i] + "\" = :" + fields[i]);
  176. }
  177. string where = String.Join(" AND ", terms.ToArray());
  178. string query = String.Format("SELECT * FROM {0} WHERE {1}",
  179. m_Realm, where);
  180. cmd.Connection = conn;
  181. cmd.CommandText = query;
  182. conn.Open();
  183. return DoQuery(cmd);
  184. }
  185. }
  186. protected T[] DoQuery(NpgsqlCommand cmd)
  187. {
  188. List<T> result = new List<T>();
  189. if (cmd.Connection == null)
  190. {
  191. cmd.Connection = new NpgsqlConnection(m_connectionString);
  192. }
  193. if (cmd.Connection.State == ConnectionState.Closed)
  194. {
  195. cmd.Connection.Open();
  196. }
  197. using (NpgsqlDataReader reader = cmd.ExecuteReader())
  198. {
  199. if (reader == null)
  200. return new T[0];
  201. CheckColumnNames(reader);
  202. while (reader.Read())
  203. {
  204. T row = new T();
  205. foreach (string name in m_Fields.Keys)
  206. {
  207. if (m_Fields[name].GetValue(row) is bool)
  208. {
  209. int v = Convert.ToInt32(reader[name]);
  210. m_Fields[name].SetValue(row, v != 0 ? true : false);
  211. }
  212. else if (m_Fields[name].GetValue(row) is UUID)
  213. {
  214. UUID uuid = UUID.Zero;
  215. UUID.TryParse(reader[name].ToString(), out uuid);
  216. m_Fields[name].SetValue(row, uuid);
  217. }
  218. else if (m_Fields[name].GetValue(row) is int)
  219. {
  220. int v = Convert.ToInt32(reader[name]);
  221. m_Fields[name].SetValue(row, v);
  222. }
  223. else
  224. {
  225. m_Fields[name].SetValue(row, reader[name]);
  226. }
  227. }
  228. if (m_DataField != null)
  229. {
  230. Dictionary<string, string> data =
  231. new Dictionary<string, string>();
  232. foreach (string col in m_ColumnNames)
  233. {
  234. data[col] = reader[col].ToString();
  235. if (data[col] == null)
  236. data[col] = String.Empty;
  237. }
  238. m_DataField.SetValue(row, data);
  239. }
  240. result.Add(row);
  241. }
  242. return result.ToArray();
  243. }
  244. }
  245. public virtual T[] Get(string where)
  246. {
  247. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  248. using (NpgsqlCommand cmd = new NpgsqlCommand())
  249. {
  250. string query = String.Format("SELECT * FROM {0} WHERE {1}",
  251. m_Realm, where);
  252. cmd.Connection = conn;
  253. cmd.CommandText = query;
  254. //m_log.WarnFormat("[PGSQLGenericTable]: SELECT {0} WHERE {1}", m_Realm, where);
  255. conn.Open();
  256. return DoQuery(cmd);
  257. }
  258. }
  259. public virtual T[] Get(string where, NpgsqlParameter parameter)
  260. {
  261. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  262. using (NpgsqlCommand cmd = new NpgsqlCommand())
  263. {
  264. string query = String.Format("SELECT * FROM {0} WHERE {1}",
  265. m_Realm, where);
  266. cmd.Connection = conn;
  267. cmd.CommandText = query;
  268. //m_log.WarnFormat("[PGSQLGenericTable]: SELECT {0} WHERE {1}", m_Realm, where);
  269. cmd.Parameters.Add(parameter);
  270. conn.Open();
  271. return DoQuery(cmd);
  272. }
  273. }
  274. public virtual bool Store(T row)
  275. {
  276. List<string> constraintFields = GetConstraints();
  277. List<KeyValuePair<string, string>> constraints = new List<KeyValuePair<string, string>>();
  278. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  279. using (NpgsqlCommand cmd = new NpgsqlCommand())
  280. {
  281. StringBuilder query = new StringBuilder();
  282. List<String> names = new List<String>();
  283. List<String> values = new List<String>();
  284. foreach (FieldInfo fi in m_Fields.Values)
  285. {
  286. names.Add(fi.Name);
  287. values.Add(":" + fi.Name);
  288. // Temporarily return more information about what field is unexpectedly null for
  289. // http://opensimulator.org/mantis/view.php?id=5403. This might be due to a bug in the
  290. // InventoryTransferModule or we may be required to substitute a DBNull here.
  291. if (fi.GetValue(row) == null)
  292. throw new NullReferenceException(
  293. string.Format(
  294. "[PGSQL GENERIC TABLE HANDLER]: Trying to store field {0} for {1} which is unexpectedly null",
  295. fi.Name, row));
  296. if (constraintFields.Count > 0 && constraintFields.Contains(fi.Name))
  297. {
  298. constraints.Add(new KeyValuePair<string, string>(fi.Name, fi.GetValue(row).ToString() ));
  299. }
  300. if (m_FieldTypes.ContainsKey(fi.Name))
  301. cmd.Parameters.Add(m_database.CreateParameter(fi.Name, fi.GetValue(row), m_FieldTypes[fi.Name]));
  302. else
  303. cmd.Parameters.Add(m_database.CreateParameter(fi.Name, fi.GetValue(row)));
  304. }
  305. if (m_DataField != null)
  306. {
  307. Dictionary<string, string> data =
  308. (Dictionary<string, string>)m_DataField.GetValue(row);
  309. foreach (KeyValuePair<string, string> kvp in data)
  310. {
  311. if (constraintFields.Count > 0 && constraintFields.Contains(kvp.Key))
  312. {
  313. constraints.Add(new KeyValuePair<string, string>(kvp.Key, kvp.Key));
  314. }
  315. names.Add(kvp.Key);
  316. values.Add(":" + kvp.Key);
  317. if (m_FieldTypes.ContainsKey(kvp.Key))
  318. cmd.Parameters.Add(m_database.CreateParameter("" + kvp.Key, kvp.Value, m_FieldTypes[kvp.Key]));
  319. else
  320. cmd.Parameters.Add(m_database.CreateParameter("" + kvp.Key, kvp.Value));
  321. }
  322. }
  323. query.AppendFormat("UPDATE {0} SET ", m_Realm);
  324. int i = 0;
  325. for (i = 0; i < names.Count - 1; i++)
  326. {
  327. query.AppendFormat("\"{0}\" = {1}, ", names[i], values[i]);
  328. }
  329. query.AppendFormat("\"{0}\" = {1} ", names[i], values[i]);
  330. if (constraints.Count > 0)
  331. {
  332. List<string> terms = new List<string>();
  333. for (int j = 0; j < constraints.Count; j++)
  334. {
  335. terms.Add(String.Format(" \"{0}\" = :{0}", constraints[j].Key));
  336. }
  337. string where = String.Join(" AND ", terms.ToArray());
  338. query.AppendFormat(" WHERE {0} ", where);
  339. }
  340. cmd.Connection = conn;
  341. cmd.CommandText = query.ToString();
  342. conn.Open();
  343. if (cmd.ExecuteNonQuery() > 0)
  344. {
  345. //m_log.WarnFormat("[PGSQLGenericTable]: Updating {0}", m_Realm);
  346. return true;
  347. }
  348. else
  349. {
  350. // assume record has not yet been inserted
  351. query = new StringBuilder();
  352. query.AppendFormat("INSERT INTO {0} (\"", m_Realm);
  353. query.Append(String.Join("\",\"", names.ToArray()));
  354. query.Append("\") values (" + String.Join(",", values.ToArray()) + ")");
  355. cmd.Connection = conn;
  356. cmd.CommandText = query.ToString();
  357. // m_log.WarnFormat("[PGSQLGenericTable]: Inserting into {0} sql {1}", m_Realm, cmd.CommandText);
  358. if (conn.State != ConnectionState.Open)
  359. conn.Open();
  360. if (cmd.ExecuteNonQuery() > 0)
  361. return true;
  362. }
  363. return false;
  364. }
  365. }
  366. public virtual bool Delete(string field, string key)
  367. {
  368. return Delete(new string[] { field }, new string[] { key });
  369. }
  370. public virtual bool Delete(string[] fields, string[] keys)
  371. {
  372. if (fields.Length != keys.Length)
  373. return false;
  374. List<string> terms = new List<string>();
  375. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  376. using (NpgsqlCommand cmd = new NpgsqlCommand())
  377. {
  378. for (int i = 0; i < fields.Length; i++)
  379. {
  380. if (m_FieldTypes.ContainsKey(fields[i]))
  381. cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i], m_FieldTypes[fields[i]]));
  382. else
  383. cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i]));
  384. terms.Add(" \"" + fields[i] + "\" = :" + fields[i]);
  385. }
  386. string where = String.Join(" AND ", terms.ToArray());
  387. string query = String.Format("DELETE FROM {0} WHERE {1}", m_Realm, where);
  388. cmd.Connection = conn;
  389. cmd.CommandText = query;
  390. conn.Open();
  391. if (cmd.ExecuteNonQuery() > 0)
  392. {
  393. //m_log.Warn("[PGSQLGenericTable]: " + deleteCommand);
  394. return true;
  395. }
  396. return false;
  397. }
  398. }
  399. public long GetCount(string field, string key)
  400. {
  401. return GetCount(new string[] { field }, new string[] { key });
  402. }
  403. public long GetCount(string[] fields, string[] keys)
  404. {
  405. if (fields.Length != keys.Length)
  406. return 0;
  407. List<string> terms = new List<string>();
  408. using (NpgsqlCommand cmd = new NpgsqlCommand())
  409. {
  410. for (int i = 0; i < fields.Length; i++)
  411. {
  412. cmd.Parameters.AddWithValue(fields[i], keys[i]);
  413. terms.Add("\"" + fields[i] + "\" = :" + fields[i]);
  414. }
  415. string where = String.Join(" and ", terms.ToArray());
  416. string query = String.Format("select count(*) from {0} where {1}",
  417. m_Realm, where);
  418. cmd.CommandText = query;
  419. Object result = DoQueryScalar(cmd);
  420. return Convert.ToInt64(result);
  421. }
  422. }
  423. public long GetCount(string where)
  424. {
  425. using (NpgsqlCommand cmd = new NpgsqlCommand())
  426. {
  427. string query = String.Format("select count(*) from {0} where {1}",
  428. m_Realm, where);
  429. cmd.CommandText = query;
  430. object result = DoQueryScalar(cmd);
  431. return Convert.ToInt64(result);
  432. }
  433. }
  434. public object DoQueryScalar(NpgsqlCommand cmd)
  435. {
  436. using (NpgsqlConnection dbcon = new NpgsqlConnection(m_ConnectionString))
  437. {
  438. dbcon.Open();
  439. cmd.Connection = dbcon;
  440. return cmd.ExecuteScalar();
  441. }
  442. }
  443. }
  444. }