PostgresqlDB.cs 12 KB

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