PGSQLGenericTableHandler.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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 bool Store(T row)
  260. {
  261. List<string> constraintFields = GetConstraints();
  262. List<KeyValuePair<string, string>> constraints = new List<KeyValuePair<string, string>>();
  263. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  264. using (NpgsqlCommand cmd = new NpgsqlCommand())
  265. {
  266. StringBuilder query = new StringBuilder();
  267. List<String> names = new List<String>();
  268. List<String> values = new List<String>();
  269. foreach (FieldInfo fi in m_Fields.Values)
  270. {
  271. names.Add(fi.Name);
  272. values.Add(":" + fi.Name);
  273. // Temporarily return more information about what field is unexpectedly null for
  274. // http://opensimulator.org/mantis/view.php?id=5403. This might be due to a bug in the
  275. // InventoryTransferModule or we may be required to substitute a DBNull here.
  276. if (fi.GetValue(row) == null)
  277. throw new NullReferenceException(
  278. string.Format(
  279. "[PGSQL GENERIC TABLE HANDLER]: Trying to store field {0} for {1} which is unexpectedly null",
  280. fi.Name, row));
  281. if (constraintFields.Count > 0 && constraintFields.Contains(fi.Name))
  282. {
  283. constraints.Add(new KeyValuePair<string, string>(fi.Name, fi.GetValue(row).ToString() ));
  284. }
  285. if (m_FieldTypes.ContainsKey(fi.Name))
  286. cmd.Parameters.Add(m_database.CreateParameter(fi.Name, fi.GetValue(row), m_FieldTypes[fi.Name]));
  287. else
  288. cmd.Parameters.Add(m_database.CreateParameter(fi.Name, fi.GetValue(row)));
  289. }
  290. if (m_DataField != null)
  291. {
  292. Dictionary<string, string> data =
  293. (Dictionary<string, string>)m_DataField.GetValue(row);
  294. foreach (KeyValuePair<string, string> kvp in data)
  295. {
  296. if (constraintFields.Count > 0 && constraintFields.Contains(kvp.Key))
  297. {
  298. constraints.Add(new KeyValuePair<string, string>(kvp.Key, kvp.Key));
  299. }
  300. names.Add(kvp.Key);
  301. values.Add(":" + kvp.Key);
  302. if (m_FieldTypes.ContainsKey(kvp.Key))
  303. cmd.Parameters.Add(m_database.CreateParameter("" + kvp.Key, kvp.Value, m_FieldTypes[kvp.Key]));
  304. else
  305. cmd.Parameters.Add(m_database.CreateParameter("" + kvp.Key, kvp.Value));
  306. }
  307. }
  308. query.AppendFormat("UPDATE {0} SET ", m_Realm);
  309. int i = 0;
  310. for (i = 0; i < names.Count - 1; i++)
  311. {
  312. query.AppendFormat("\"{0}\" = {1}, ", names[i], values[i]);
  313. }
  314. query.AppendFormat("\"{0}\" = {1} ", names[i], values[i]);
  315. if (constraints.Count > 0)
  316. {
  317. List<string> terms = new List<string>();
  318. for (int j = 0; j < constraints.Count; j++)
  319. {
  320. terms.Add(String.Format(" \"{0}\" = :{0}", constraints[j].Key));
  321. }
  322. string where = String.Join(" AND ", terms.ToArray());
  323. query.AppendFormat(" WHERE {0} ", where);
  324. }
  325. cmd.Connection = conn;
  326. cmd.CommandText = query.ToString();
  327. conn.Open();
  328. if (cmd.ExecuteNonQuery() > 0)
  329. {
  330. //m_log.WarnFormat("[PGSQLGenericTable]: Updating {0}", m_Realm);
  331. return true;
  332. }
  333. else
  334. {
  335. // assume record has not yet been inserted
  336. query = new StringBuilder();
  337. query.AppendFormat("INSERT INTO {0} (\"", m_Realm);
  338. query.Append(String.Join("\",\"", names.ToArray()));
  339. query.Append("\") values (" + String.Join(",", values.ToArray()) + ")");
  340. cmd.Connection = conn;
  341. cmd.CommandText = query.ToString();
  342. // m_log.WarnFormat("[PGSQLGenericTable]: Inserting into {0} sql {1}", m_Realm, cmd.CommandText);
  343. if (conn.State != ConnectionState.Open)
  344. conn.Open();
  345. if (cmd.ExecuteNonQuery() > 0)
  346. return true;
  347. }
  348. return false;
  349. }
  350. }
  351. public virtual bool Delete(string field, string key)
  352. {
  353. return Delete(new string[] { field }, new string[] { key });
  354. }
  355. public virtual bool Delete(string[] fields, string[] keys)
  356. {
  357. if (fields.Length != keys.Length)
  358. return false;
  359. List<string> terms = new List<string>();
  360. using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
  361. using (NpgsqlCommand cmd = new NpgsqlCommand())
  362. {
  363. for (int i = 0; i < fields.Length; i++)
  364. {
  365. if (m_FieldTypes.ContainsKey(fields[i]))
  366. cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i], m_FieldTypes[fields[i]]));
  367. else
  368. cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i]));
  369. terms.Add(" \"" + fields[i] + "\" = :" + fields[i]);
  370. }
  371. string where = String.Join(" AND ", terms.ToArray());
  372. string query = String.Format("DELETE FROM {0} WHERE {1}", m_Realm, where);
  373. cmd.Connection = conn;
  374. cmd.CommandText = query;
  375. conn.Open();
  376. if (cmd.ExecuteNonQuery() > 0)
  377. {
  378. //m_log.Warn("[PGSQLGenericTable]: " + deleteCommand);
  379. return true;
  380. }
  381. return false;
  382. }
  383. }
  384. public long GetCount(string field, string key)
  385. {
  386. return GetCount(new string[] { field }, new string[] { key });
  387. }
  388. public long GetCount(string[] fields, string[] keys)
  389. {
  390. if (fields.Length != keys.Length)
  391. return 0;
  392. List<string> terms = new List<string>();
  393. using (NpgsqlCommand cmd = new NpgsqlCommand())
  394. {
  395. for (int i = 0; i < fields.Length; i++)
  396. {
  397. cmd.Parameters.AddWithValue(fields[i], keys[i]);
  398. terms.Add("\"" + fields[i] + "\" = :" + fields[i]);
  399. }
  400. string where = String.Join(" and ", terms.ToArray());
  401. string query = String.Format("select count(*) from {0} where {1}",
  402. m_Realm, where);
  403. cmd.CommandText = query;
  404. Object result = DoQueryScalar(cmd);
  405. return Convert.ToInt64(result);
  406. }
  407. }
  408. public long GetCount(string where)
  409. {
  410. using (NpgsqlCommand cmd = new NpgsqlCommand())
  411. {
  412. string query = String.Format("select count(*) from {0} where {1}",
  413. m_Realm, where);
  414. cmd.CommandText = query;
  415. object result = DoQueryScalar(cmd);
  416. return Convert.ToInt64(result);
  417. }
  418. }
  419. public object DoQueryScalar(NpgsqlCommand cmd)
  420. {
  421. using (NpgsqlConnection dbcon = new NpgsqlConnection(m_ConnectionString))
  422. {
  423. dbcon.Open();
  424. cmd.Connection = dbcon;
  425. return cmd.ExecuteScalar();
  426. }
  427. }
  428. }
  429. }