PostgresqlDB.cs 11 KB

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