PostgresqlDB.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Npgsql;
  6. using Aitex.Core.RT.Log;
  7. using System.Data;
  8. using Aitex.Core.Utilities;
  9. using DocumentFormat.OpenXml.Office.Word;
  10. namespace Aitex.Core.RT.DBCore
  11. {
  12. public enum DataBaseStatus
  13. {
  14. Close,
  15. Open,
  16. Error
  17. }
  18. public class PostgresqlDB
  19. {
  20. NpgsqlConnection _conn;
  21. string _connectionString;
  22. string _dbName;
  23. Retry _retryConnection = new Retry();
  24. private int _closeMaxTime = 4;
  25. private int _closeTime = 0;
  26. public DataBaseStatus DBStatus
  27. {
  28. get
  29. {
  30. //超过允许异常关闭的次数
  31. if (_closeTime >= _closeMaxTime)
  32. return DataBaseStatus.Error;
  33. else
  34. return (_conn != null && _conn.State == ConnectionState.Open) ? DataBaseStatus.Open : DataBaseStatus.Close;
  35. }
  36. }
  37. public PostgresqlDB()
  38. {
  39. }
  40. public bool Open(string connectionString, string dbName)
  41. {
  42. _connectionString = connectionString;
  43. _dbName = dbName;
  44. bool result = true;
  45. try
  46. {
  47. if (_conn != null)
  48. _conn.Close();
  49. _conn = new NpgsqlConnection(connectionString);
  50. _conn.Open();
  51. if (!string.IsNullOrEmpty(dbName))
  52. CreateDBIfNotExisted(dbName);
  53. }
  54. catch (Exception ex)
  55. {
  56. if (_conn != null)
  57. {
  58. _conn.Close();
  59. _conn = null;
  60. }
  61. result = false;
  62. LOG.WriteExeption(ex);
  63. }
  64. _retryConnection.Result = result;
  65. //if (_retryConnection.IsErrored)
  66. return result;
  67. }
  68. bool Open()
  69. {
  70. return Open(_connectionString, _dbName);
  71. }
  72. void PrepareCommand(NpgsqlCommand cmd, NpgsqlConnection conn, string cmdText, params object[] p)
  73. {
  74. cmd.Parameters.Clear();
  75. cmd.Connection = conn;
  76. cmd.CommandText = cmdText;
  77. cmd.CommandType = CommandType.Text;
  78. if (p != null)
  79. {
  80. foreach (object parm in p)
  81. cmd.Parameters.AddWithValue(string.Empty, parm);
  82. }
  83. }
  84. public int ExecuteNonQuery(string cmdText, params object[] p)
  85. {
  86. try
  87. {
  88. using (NpgsqlCommand command = new NpgsqlCommand())
  89. {
  90. PrepareCommand(command, _conn, cmdText, p);
  91. return command.ExecuteNonQuery();
  92. }
  93. }
  94. catch
  95. {
  96. _closeTime++;
  97. Close();
  98. throw;
  99. }
  100. }
  101. public DataSet ExecuteDataset(string cmdText, params object[] p)
  102. {
  103. try
  104. {
  105. DataSet ds = new DataSet();
  106. using (var connection = new NpgsqlConnection(_connectionString))
  107. {
  108. connection.Open();
  109. connection.ChangeDatabase(_dbName);
  110. using (NpgsqlCommand command = new NpgsqlCommand())
  111. {
  112. try
  113. {
  114. PrepareCommand(command, connection, cmdText, p);
  115. NpgsqlDataAdapter da = new NpgsqlDataAdapter(command);
  116. da.Fill(ds);
  117. }
  118. catch (Exception ex)
  119. {
  120. LOG.WriteExeption("执行查询出错," + cmdText, ex);
  121. }
  122. }
  123. }
  124. return ds;
  125. }
  126. catch (Exception ex)
  127. {
  128. LOG.WriteExeption("执行查询出错," + cmdText, ex);
  129. }
  130. return null;
  131. }
  132. public NpgsqlDataReader ExecuteReader(string cmdText, params object[] p)
  133. {
  134. try
  135. {
  136. using (NpgsqlCommand command = new NpgsqlCommand())
  137. {
  138. PrepareCommand(command, _conn, cmdText, p);
  139. return command.ExecuteReader(CommandBehavior.CloseConnection);
  140. }
  141. }
  142. catch
  143. {
  144. Close();
  145. throw;
  146. }
  147. }
  148. public int GetAllCount(string cmdText, params object[] p)
  149. {
  150. using (var connection = new NpgsqlConnection(_connectionString))
  151. {
  152. connection.Open();
  153. connection.ChangeDatabase(_dbName);
  154. using (NpgsqlCommand command = new NpgsqlCommand())
  155. {
  156. try
  157. {
  158. PrepareCommand(command, connection, cmdText, p);
  159. return Convert.ToInt32( command.ExecuteScalar());
  160. }
  161. catch (Exception ex)
  162. {
  163. LOG.WriteExeption("执行查询出错," + cmdText, ex);
  164. return 0;
  165. }
  166. }
  167. }
  168. //using (var connection = new NpgsqlConnection(_connectionString))
  169. //{
  170. // using (NpgsqlCommand command = new NpgsqlCommand(cmdText,connection))
  171. // {
  172. // try
  173. // {
  174. // connection.Open();
  175. // object obj = command.ExecuteScalar();
  176. // return (Int32)command.ExecuteScalar();
  177. // }
  178. // catch (Exception ex)
  179. // {
  180. // LOG.WriteExeption("执行查询出错," + cmdText, ex);
  181. // return 0;
  182. // }
  183. // }
  184. //}
  185. }
  186. public bool ActiveConnection()
  187. {
  188. if (_conn != null && _conn.State == ConnectionState.Open)
  189. return true;
  190. return Open();
  191. }
  192. public void Close()
  193. {
  194. try
  195. {
  196. if (_conn != null)
  197. _conn.Close();
  198. _conn = null;
  199. }
  200. catch (Exception ex)
  201. {
  202. LOG.WriteExeption(ex);
  203. }
  204. }
  205. public void CreateDBIfNotExisted(string db)
  206. {
  207. NpgsqlDataReader reader =
  208. ExecuteReader(string.Format(@"select datname from pg_catalog.pg_database where datname='{0}'", db));
  209. if (!reader.HasRows)
  210. {
  211. string sql = string.Format(@"
  212. CREATE DATABASE {0}
  213. WITH OWNER = postgres
  214. ENCODING = 'UTF8'
  215. TABLESPACE = pg_default
  216. CONNECTION LIMIT = -1", db);
  217. ExecuteNonQuery(sql);
  218. }
  219. try
  220. {
  221. _conn.ChangeDatabase(db);
  222. }
  223. catch
  224. {
  225. _conn.Close();
  226. throw;
  227. }
  228. }
  229. public void CreateTableIndexIfNotExisted(string table, string index, string sql)
  230. {
  231. NpgsqlDataReader reader = ExecuteReader($"select* from pg_indexes where tablename='{table}' and indexname = '{index}'");
  232. if (!reader.HasRows)
  233. {
  234. ExecuteNonQuery(sql);
  235. }
  236. }
  237. public void CreateTableIfNotExisted(string table, Dictionary<string, Type> columns, bool addPID,
  238. string primaryKey)
  239. {
  240. NpgsqlDataReader reader =
  241. ExecuteReader(
  242. string.Format(@"select column_name from information_schema.columns where table_name = '{0}'",
  243. table));
  244. if (!reader.HasRows)
  245. {
  246. string cols = addPID ? " \"PID\" serial NOT NULL," : "";
  247. foreach (var item in columns)
  248. {
  249. if (item.Value == typeof(int))
  250. cols += string.Format("\"{0}\" integer,", item.Key);
  251. else if (item.Value == typeof(string))
  252. cols += string.Format("\"{0}\" text,", item.Key);
  253. else if (item.Value == typeof(DateTime))
  254. cols += string.Format("\"{0}\" timestamp without time zone,", item.Key);
  255. else if (item.Value == typeof(bool))
  256. cols += string.Format("\"{0}\" boolean,", item.Key);
  257. else if (item.Value == typeof(float))
  258. cols += string.Format("\"{0}\" real,", item.Key);
  259. }
  260. if (string.IsNullOrEmpty(primaryKey))
  261. {
  262. if (cols.LastIndexOf(',') == cols.Length - 1)
  263. cols = cols.Remove(cols.Length - 1);
  264. }
  265. else
  266. {
  267. cols += string.Format("CONSTRAINT \"{0}_pkey\" PRIMARY KEY (\"{1}\" )", table, primaryKey);
  268. }
  269. ExecuteNonQuery(string.Format("CREATE TABLE \"{0}\"({1})WITH ( OIDS=FALSE );", table, cols));
  270. }
  271. else
  272. {
  273. CreateTableColumn(table, columns);
  274. }
  275. }
  276. public void CreateTableColumn(string tableName, Dictionary<string, Type> columns)
  277. {
  278. try
  279. {
  280. //query if table already exist?
  281. string sqlTblDefine =
  282. string.Format("select column_name from information_schema.columns where table_name = '{0}';",
  283. tableName);
  284. NpgsqlCommand cmdTblDefine = new NpgsqlCommand(sqlTblDefine, _conn);
  285. var tblDefineData = cmdTblDefine.ExecuteReader();
  286. string tblAlertString = string.Empty;
  287. List<string> colNameList = new List<string>();
  288. while (tblDefineData.Read())
  289. {
  290. for (int i = 0; i < tblDefineData.FieldCount; i++)
  291. colNameList.Add(tblDefineData[i].ToString());
  292. }
  293. tblDefineData.Close();
  294. if (colNameList.Count > 0)
  295. {
  296. //table exist
  297. foreach (var column in columns)
  298. {
  299. if (!colNameList.Contains(column.Key))
  300. {
  301. if (column.Value == typeof(Boolean))
  302. {
  303. tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};",
  304. tableName, column.Key, "Boolean");
  305. }
  306. else if (column.Value == typeof(double) || column.Value == typeof(float))
  307. {
  308. tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};",
  309. tableName, column.Key, "real");
  310. }
  311. else if (column.Value == typeof(DateTime))
  312. {
  313. tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};",
  314. tableName, column.Key, "timestamp without time zone");
  315. }
  316. else if (column.Value == typeof(int) || column.Value == typeof(ushort) ||
  317. column.Value == typeof(short))
  318. {
  319. tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};",
  320. tableName, column.Key, "integer");
  321. }
  322. else
  323. {
  324. tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};",
  325. tableName, column.Key, "text");
  326. }
  327. }
  328. }
  329. if (!string.IsNullOrEmpty(tblAlertString))
  330. {
  331. try
  332. {
  333. NpgsqlCommand alertTblCmd = new NpgsqlCommand(tblAlertString, _conn);
  334. alertTblCmd.ExecuteNonQuery();
  335. }
  336. catch (Exception ex)
  337. {
  338. LOG.WriteExeption(ex);
  339. }
  340. }
  341. }
  342. }
  343. catch (Exception ex)
  344. {
  345. LOG.WriteExeption(ex);
  346. }
  347. }
  348. }
  349. }