PostgresqlDB.cs 11 KB

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