PostgresqlDB.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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 int GetCount(string cmdText, params object[] p)
  136. {
  137. try
  138. {
  139. using (var connection = new NpgsqlConnection(_connectionString))
  140. using (NpgsqlCommand command = new NpgsqlCommand())
  141. {
  142. connection.Open();
  143. connection.ChangeDatabase(_dbName);
  144. PrepareCommand(command, connection, cmdText, p);
  145. return Convert.ToInt32(command.ExecuteScalar());
  146. }
  147. }
  148. catch (Exception ex)
  149. {
  150. Close();
  151. LOG.Write($"DB failed to execute:{cmdText} Exception:{ex}");
  152. return 0;
  153. }
  154. }
  155. public bool ActiveConnection()
  156. {
  157. if (_conn!=null && _conn.State == ConnectionState.Open)
  158. return true;
  159. return Open();
  160. }
  161. public void Close()
  162. {
  163. try
  164. {
  165. if (_conn != null)
  166. _conn.Close();
  167. _conn = null;
  168. _dbFailed = false;
  169. }
  170. catch (Exception ex)
  171. {
  172. if (!_dbFailed)
  173. {
  174. LOG.Write(ex);
  175. _dbFailed = true;
  176. }
  177. }
  178. }
  179. public void CreateDBIfNotExisted(string db)
  180. {
  181. NpgsqlDataReader reader = ExecuteReader(string.Format(@"select datname from pg_catalog.pg_database where datname='{0}'", db));
  182. if (!reader.HasRows)
  183. {
  184. string sql = string.Format(@"
  185. CREATE DATABASE {0}
  186. WITH OWNER = postgres
  187. ENCODING = 'UTF8'
  188. TABLESPACE = pg_default
  189. CONNECTION LIMIT = -1", db);
  190. ExecuteNonQuery(sql);
  191. }
  192. try
  193. {
  194. _conn.ChangeDatabase(db);
  195. }
  196. catch
  197. {
  198. _conn.Close();
  199. throw;
  200. }
  201. }
  202. public void CreateTableIndexIfNotExisted(string table, string index, string sql)
  203. {
  204. NpgsqlDataReader reader = ExecuteReader($"select* from pg_indexes where tablename='{table}' and indexname = '{index}'");
  205. if (!reader.HasRows)
  206. {
  207. ExecuteNonQuery(sql);
  208. }
  209. }
  210. public void CreateTableIfNotExisted(string table, Dictionary<string, Type> columns, bool addPID, string primaryKey)
  211. {
  212. NpgsqlDataReader reader = ExecuteReader(string.Format(@"select column_name from information_schema.columns where table_name = '{0}'", table));
  213. if (!reader.HasRows)
  214. {
  215. string cols = addPID ? " \"PID\" serial NOT NULL," : "";
  216. foreach (var item in columns)
  217. {
  218. if (item.Value == typeof(int) || item.Value == typeof(ushort) || item.Value == typeof(short))
  219. cols += string.Format("\"{0}\" integer,", item.Key);
  220. else if (item.Value == typeof(double) || item.Value == typeof(float))
  221. cols += string.Format("\"{0}\" real,", item.Key);
  222. else if (item.Value == typeof(string))
  223. cols += string.Format("\"{0}\" text,", item.Key);
  224. else if (item.Value == typeof(DateTime))
  225. cols += string.Format("\"{0}\" timestamp without time zone,", item.Key);
  226. else if (item.Value == typeof(bool))
  227. cols += string.Format("\"{0}\" boolean,", item.Key);
  228. }
  229. if (string.IsNullOrEmpty(primaryKey))
  230. {
  231. if (cols.LastIndexOf(',') == cols.Length-1)
  232. cols = cols.Remove(cols.Length - 1);
  233. }else
  234. {
  235. cols += string.Format("CONSTRAINT \"{0}_pkey\" PRIMARY KEY (\"{1}\" )", table, primaryKey);
  236. }
  237. ExecuteNonQuery(string.Format("CREATE TABLE \"{0}\"({1})WITH ( OIDS=FALSE );", table, cols));
  238. }
  239. else
  240. {
  241. CreateTableColumn(table, columns);
  242. }
  243. }
  244. public void CreateTableColumn(string tableName, Dictionary<string, Type> columns )
  245. {
  246. try
  247. {
  248. //query if table already exist?
  249. string sqlTblDefine = string.Format("select column_name from information_schema.columns where table_name = '{0}';", tableName);
  250. NpgsqlCommand cmdTblDefine = new NpgsqlCommand(sqlTblDefine, _conn);
  251. var tblDefineData = cmdTblDefine.ExecuteReader();
  252. string tblAlertString = string.Empty;
  253. List<string> colNameList = new List<string>();
  254. while (tblDefineData.Read())
  255. {
  256. for (int i = 0; i < tblDefineData.FieldCount; i++)
  257. colNameList.Add(tblDefineData[i].ToString());
  258. }
  259. tblDefineData.Close();
  260. if (colNameList.Count > 0)
  261. {
  262. //table exist
  263. foreach (var column in columns)
  264. {
  265. if (!colNameList.Contains(column.Key))
  266. {
  267. if (column.Value == typeof(Boolean))
  268. {
  269. tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};", tableName, column.Key, "Boolean");
  270. }
  271. else if (column.Value == typeof(double) || column.Value == typeof(float) )
  272. {
  273. tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};", tableName, column.Key, "real");
  274. }
  275. else if (column.Value == typeof(DateTime) )
  276. {
  277. tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};", tableName, column.Key, "timestamp without time zone");
  278. }
  279. else if (column.Value == typeof(int) || column.Value == typeof(ushort) || column.Value == typeof(short))
  280. {
  281. tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};", tableName, column.Key, "integer");
  282. }
  283. else
  284. {
  285. tblAlertString += string.Format("ALTER TABLE \"{0}\" ADD COLUMN \"{1}\" {2};", tableName, column.Key, "text");
  286. }
  287. }
  288. }
  289. if (!string.IsNullOrEmpty(tblAlertString))
  290. {
  291. try
  292. {
  293. NpgsqlCommand alertTblCmd = new NpgsqlCommand(tblAlertString, _conn);
  294. alertTblCmd.ExecuteNonQuery();
  295. _dbFailed = false;
  296. }
  297. catch (Exception ex)
  298. {
  299. if (!_dbFailed)
  300. {
  301. LOG.Write(ex);
  302. _dbFailed = true;
  303. }
  304. }
  305. }
  306. }
  307. _dbFailed = true;
  308. }
  309. catch (Exception ex)
  310. {
  311. if (!_dbFailed)
  312. {
  313. LOG.Write(ex);
  314. _dbFailed = true;
  315. }
  316. }
  317. }
  318. }
  319. }