PGSQLGenericTableHandler.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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
  125. a.attname as column_name
  126. from
  127. pg_class t,
  128. pg_class i,
  129. pg_index ix,
  130. pg_attribute a
  131. where
  132. t.oid = ix.indrelid
  133. and i.oid = ix.indexrelid
  134. and a.attrelid = t.oid
  135. and a.attnum = ANY(ix.indkey)
  136. and t.relkind = 'r'
  137. and ix.indisunique = true
  138. and t.relname = lower('{0}')
  139. ;", m_Realm);
  140. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  141. using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn))
  142. {
  143. conn.Open();
  144. using (NpgsqlDataReader rdr = cmd.ExecuteReader())
  145. {
  146. while (rdr.Read())
  147. {
  148. // query produces 0 to many rows of single column, so always add the first item in each row
  149. constraints.Add((string)rdr[0]);
  150. }
  151. }
  152. return constraints;
  153. }
  154. }
  155. public virtual T[] Get(string field, string key)
  156. {
  157. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  158. using (NpgsqlCommand cmd = new NpgsqlCommand())
  159. {
  160. if ( m_FieldTypes.ContainsKey(field) )
  161. cmd.Parameters.Add(m_database.CreateParameter(field, key, m_FieldTypes[field]));
  162. else
  163. cmd.Parameters.Add(m_database.CreateParameter(field, key));
  164. string query = String.Format("SELECT * FROM {0} WHERE \"{1}\" = :{1}", m_Realm, field, field);
  165. cmd.Connection = conn;
  166. cmd.CommandText = query;
  167. conn.Open();
  168. return DoQuery(cmd);
  169. }
  170. }
  171. public virtual T[] Get(string field, string[] keys)
  172. {
  173. int flen = keys.Length;
  174. if(flen == 0)
  175. return new T[0];
  176. int flast = flen - 1;
  177. StringBuilder sb = new StringBuilder(1024);
  178. sb.AppendFormat("select * from {0} where {1} IN ('", m_Realm, field);
  179. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  180. using (NpgsqlCommand cmd = new NpgsqlCommand())
  181. {
  182. for (int i = 0 ; i < flen ; i++)
  183. {
  184. sb.Append(keys[i]);
  185. if(i < flast)
  186. sb.Append("','");
  187. else
  188. sb.Append("')");
  189. }
  190. string query = sb.ToString();
  191. cmd.Connection = conn;
  192. cmd.CommandText = query;
  193. conn.Open();
  194. return DoQuery(cmd);
  195. }
  196. }
  197. public virtual T[] Get(string[] fields, string[] keys)
  198. {
  199. if (fields.Length != keys.Length)
  200. return new T[0];
  201. List<string> terms = new List<string>();
  202. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  203. using (NpgsqlCommand cmd = new NpgsqlCommand())
  204. {
  205. for (int i = 0; i < fields.Length; i++)
  206. {
  207. if ( m_FieldTypes.ContainsKey(fields[i]) )
  208. cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i], m_FieldTypes[fields[i]]));
  209. else
  210. cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i]));
  211. terms.Add(" \"" + fields[i] + "\" = :" + fields[i]);
  212. }
  213. string where = String.Join(" AND ", terms.ToArray());
  214. string query = String.Format("SELECT * FROM {0} WHERE {1}",
  215. m_Realm, where);
  216. cmd.Connection = conn;
  217. cmd.CommandText = query;
  218. conn.Open();
  219. return DoQuery(cmd);
  220. }
  221. }
  222. protected T[] DoQuery(NpgsqlCommand cmd)
  223. {
  224. List<T> result = new List<T>();
  225. if (cmd.Connection == null)
  226. {
  227. cmd.Connection = new NpgsqlConnection(m_connectionString);
  228. }
  229. if (cmd.Connection.State == ConnectionState.Closed)
  230. {
  231. cmd.Connection.Open();
  232. }
  233. using (NpgsqlDataReader reader = cmd.ExecuteReader())
  234. {
  235. if (reader == null)
  236. return new T[0];
  237. CheckColumnNames(reader);
  238. while (reader.Read())
  239. {
  240. T row = new T();
  241. foreach (string name in m_Fields.Keys)
  242. {
  243. if (m_Fields[name].GetValue(row) is bool)
  244. {
  245. int v = Convert.ToInt32(reader[name]);
  246. m_Fields[name].SetValue(row, v != 0 ? true : false);
  247. }
  248. else if (m_Fields[name].GetValue(row) is UUID)
  249. {
  250. UUID uuid = UUID.Zero;
  251. UUID.TryParse(reader[name].ToString(), out uuid);
  252. m_Fields[name].SetValue(row, uuid);
  253. }
  254. else if (m_Fields[name].GetValue(row) is int)
  255. {
  256. int v = Convert.ToInt32(reader[name]);
  257. m_Fields[name].SetValue(row, v);
  258. }
  259. else
  260. {
  261. m_Fields[name].SetValue(row, reader[name]);
  262. }
  263. }
  264. if (m_DataField != null)
  265. {
  266. Dictionary<string, string> data =
  267. new Dictionary<string, string>();
  268. foreach (string col in m_ColumnNames)
  269. {
  270. data[col] = reader[col].ToString();
  271. if (data[col] == null)
  272. data[col] = String.Empty;
  273. }
  274. m_DataField.SetValue(row, data);
  275. }
  276. result.Add(row);
  277. }
  278. return result.ToArray();
  279. }
  280. }
  281. public virtual T[] Get(string where)
  282. {
  283. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  284. using (NpgsqlCommand cmd = new NpgsqlCommand())
  285. {
  286. string query = String.Format("SELECT * FROM {0} WHERE {1}",
  287. m_Realm, where);
  288. cmd.Connection = conn;
  289. cmd.CommandText = query;
  290. //m_log.WarnFormat("[PGSQLGenericTable]: SELECT {0} WHERE {1}", m_Realm, where);
  291. conn.Open();
  292. return DoQuery(cmd);
  293. }
  294. }
  295. public virtual T[] Get(string where, NpgsqlParameter parameter)
  296. {
  297. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  298. using (NpgsqlCommand cmd = new NpgsqlCommand())
  299. {
  300. string query = String.Format("SELECT * FROM {0} WHERE {1}",
  301. m_Realm, where);
  302. cmd.Connection = conn;
  303. cmd.CommandText = query;
  304. //m_log.WarnFormat("[PGSQLGenericTable]: SELECT {0} WHERE {1}", m_Realm, where);
  305. cmd.Parameters.Add(parameter);
  306. conn.Open();
  307. return DoQuery(cmd);
  308. }
  309. }
  310. public virtual bool Store(T row)
  311. {
  312. List<string> constraintFields = GetConstraints();
  313. List<KeyValuePair<string, string>> constraints = new List<KeyValuePair<string, string>>();
  314. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  315. using (NpgsqlCommand cmd = new NpgsqlCommand())
  316. {
  317. StringBuilder query = new StringBuilder();
  318. List<String> names = new List<String>();
  319. List<String> values = new List<String>();
  320. foreach (FieldInfo fi in m_Fields.Values)
  321. {
  322. names.Add(fi.Name);
  323. values.Add(":" + fi.Name);
  324. // Temporarily return more information about what field is unexpectedly null for
  325. // http://opensimulator.org/mantis/view.php?id=5403. This might be due to a bug in the
  326. // InventoryTransferModule or we may be required to substitute a DBNull here.
  327. if (fi.GetValue(row) == null)
  328. throw new NullReferenceException(
  329. string.Format(
  330. "[PGSQL GENERIC TABLE HANDLER]: Trying to store field {0} for {1} which is unexpectedly null",
  331. fi.Name, row));
  332. if (constraintFields.Count > 0 && constraintFields.Contains(fi.Name))
  333. {
  334. constraints.Add(new KeyValuePair<string, string>(fi.Name, fi.GetValue(row).ToString() ));
  335. }
  336. if (m_FieldTypes.ContainsKey(fi.Name))
  337. cmd.Parameters.Add(m_database.CreateParameter(fi.Name, fi.GetValue(row), m_FieldTypes[fi.Name]));
  338. else
  339. cmd.Parameters.Add(m_database.CreateParameter(fi.Name, fi.GetValue(row)));
  340. }
  341. if (m_DataField != null)
  342. {
  343. Dictionary<string, string> data =
  344. (Dictionary<string, string>)m_DataField.GetValue(row);
  345. foreach (KeyValuePair<string, string> kvp in data)
  346. {
  347. if (constraintFields.Count > 0 && constraintFields.Contains(kvp.Key))
  348. {
  349. constraints.Add(new KeyValuePair<string, string>(kvp.Key, kvp.Key));
  350. }
  351. names.Add(kvp.Key);
  352. values.Add(":" + kvp.Key);
  353. if (m_FieldTypes.ContainsKey(kvp.Key))
  354. cmd.Parameters.Add(m_database.CreateParameter("" + kvp.Key, kvp.Value, m_FieldTypes[kvp.Key]));
  355. else
  356. cmd.Parameters.Add(m_database.CreateParameter("" + kvp.Key, kvp.Value));
  357. }
  358. }
  359. query.AppendFormat("UPDATE {0} SET ", m_Realm);
  360. int i = 0;
  361. for (i = 0; i < names.Count - 1; i++)
  362. {
  363. query.AppendFormat("\"{0}\" = {1}, ", names[i], values[i]);
  364. }
  365. query.AppendFormat("\"{0}\" = {1} ", names[i], values[i]);
  366. if (constraints.Count > 0)
  367. {
  368. List<string> terms = new List<string>();
  369. for (int j = 0; j < constraints.Count; j++)
  370. {
  371. terms.Add(String.Format(" \"{0}\" = :{0}", constraints[j].Key));
  372. }
  373. string where = String.Join(" AND ", terms.ToArray());
  374. query.AppendFormat(" WHERE {0} ", where);
  375. }
  376. cmd.Connection = conn;
  377. cmd.CommandText = query.ToString();
  378. conn.Open();
  379. if (cmd.ExecuteNonQuery() > 0)
  380. {
  381. //m_log.WarnFormat("[PGSQLGenericTable]: Updating {0}", m_Realm);
  382. return true;
  383. }
  384. else
  385. {
  386. // assume record has not yet been inserted
  387. query = new StringBuilder();
  388. query.AppendFormat("INSERT INTO {0} (\"", m_Realm);
  389. query.Append(String.Join("\",\"", names.ToArray()));
  390. query.Append("\") values (" + String.Join(",", values.ToArray()) + ")");
  391. cmd.Connection = conn;
  392. cmd.CommandText = query.ToString();
  393. // m_log.WarnFormat("[PGSQLGenericTable]: Inserting into {0} sql {1}", m_Realm, cmd.CommandText);
  394. if (conn.State != ConnectionState.Open)
  395. conn.Open();
  396. if (cmd.ExecuteNonQuery() > 0)
  397. return true;
  398. }
  399. return false;
  400. }
  401. }
  402. public virtual bool Delete(string field, string key)
  403. {
  404. return Delete(new string[] { field }, new string[] { key });
  405. }
  406. public virtual bool Delete(string[] fields, string[] keys)
  407. {
  408. if (fields.Length != keys.Length)
  409. return false;
  410. List<string> terms = new List<string>();
  411. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  412. using (NpgsqlCommand cmd = new NpgsqlCommand())
  413. {
  414. for (int i = 0; i < fields.Length; i++)
  415. {
  416. if (m_FieldTypes.ContainsKey(fields[i]))
  417. cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i], m_FieldTypes[fields[i]]));
  418. else
  419. cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i]));
  420. terms.Add(" \"" + fields[i] + "\" = :" + fields[i]);
  421. }
  422. string where = String.Join(" AND ", terms.ToArray());
  423. string query = String.Format("DELETE FROM {0} WHERE {1}", m_Realm, where);
  424. cmd.Connection = conn;
  425. cmd.CommandText = query;
  426. conn.Open();
  427. if (cmd.ExecuteNonQuery() > 0)
  428. {
  429. //m_log.Warn("[PGSQLGenericTable]: " + deleteCommand);
  430. return true;
  431. }
  432. return false;
  433. }
  434. }
  435. public long GetCount(string field, string key)
  436. {
  437. return GetCount(new string[] { field }, new string[] { key });
  438. }
  439. public long GetCount(string[] fields, string[] keys)
  440. {
  441. if (fields.Length != keys.Length)
  442. return 0;
  443. List<string> terms = new List<string>();
  444. using (NpgsqlCommand cmd = new NpgsqlCommand())
  445. {
  446. for (int i = 0; i < fields.Length; i++)
  447. {
  448. cmd.Parameters.AddWithValue(fields[i], keys[i]);
  449. terms.Add("\"" + fields[i] + "\" = :" + fields[i]);
  450. }
  451. string where = String.Join(" and ", terms.ToArray());
  452. string query = String.Format("select count(*) from {0} where {1}",
  453. m_Realm, where);
  454. cmd.CommandText = query;
  455. Object result = DoQueryScalar(cmd);
  456. return Convert.ToInt64(result);
  457. }
  458. }
  459. public long GetCount(string where)
  460. {
  461. using (NpgsqlCommand cmd = new NpgsqlCommand())
  462. {
  463. string query = String.Format("select count(*) from {0} where {1}",
  464. m_Realm, where);
  465. cmd.CommandText = query;
  466. object result = DoQueryScalar(cmd);
  467. return Convert.ToInt64(result);
  468. }
  469. }
  470. public object DoQueryScalar(NpgsqlCommand cmd)
  471. {
  472. using (NpgsqlConnection dbcon = new NpgsqlConnection(m_ConnectionString))
  473. {
  474. dbcon.Open();
  475. cmd.Connection = dbcon;
  476. return cmd.ExecuteScalar();
  477. }
  478. }
  479. }
  480. }