PostgresqlDB.cs 12 KB

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