TDengineDbMaintenance.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. using SqlSugar;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Linq;
  6. namespace SqlSugar.BzTDengineCore
  7. {
  8. public class TDengineDbMaintenance : DbMaintenanceProvider
  9. {
  10. #region DML
  11. protected override string GetViewInfoListSql => throw new NotImplementedException();
  12. protected override string GetDataBaseSql
  13. {
  14. get
  15. {
  16. return "show databases";
  17. }
  18. }
  19. protected override string GetColumnInfosByTableNameSql
  20. {
  21. get
  22. {
  23. throw new NotSupportedException("TDengineCode暂时不支持DbFirst等方法,还在开发");
  24. }
  25. }
  26. protected override string GetTableInfoListSql
  27. {
  28. get
  29. {
  30. var dt = GetSTables();
  31. List<string> sb = new List<string>();
  32. foreach (DataRow item in dt.Rows)
  33. {
  34. sb.Add($" SELECT '{item["stable_name"].ObjToString().ToSqlFilter()}' AS NAME ");
  35. }
  36. var dt2 = GetTables();
  37. foreach (DataRow item in dt2.Rows)
  38. {
  39. sb.Add($" SELECT '{item["table_name"].ObjToString().ToSqlFilter()}' AS NAME ");
  40. }
  41. var result = string.Join(" UNION ALL ", sb);
  42. if (string.IsNullOrEmpty(result))
  43. {
  44. result = " SELECT 'NoTables' AS Name ";
  45. }
  46. return result;
  47. }
  48. }
  49. #endregion DML
  50. #region DDL
  51. protected override string CreateDataBaseSql
  52. {
  53. get
  54. {
  55. return "CREATE DATABASE IF NOT EXISTS {0} WAL_RETENTION_PERIOD 3600";
  56. }
  57. }
  58. protected override string AddPrimaryKeySql
  59. {
  60. get
  61. {
  62. return "ALTER TABLE {0} ADD PRIMARY KEY({2}) /*{1}*/";
  63. }
  64. }
  65. protected override string AddColumnToTableSql
  66. {
  67. get
  68. {
  69. return "ALTER TABLE {0} ADD COLUMN {1} {2}{3} {4} {5} {6}";
  70. }
  71. }
  72. protected override string AlterColumnToTableSql
  73. {
  74. get
  75. {
  76. return "alter table {0} MODIFY COLUMN {1} {2}{3} {4} {5} {6}";
  77. }
  78. }
  79. protected override string BackupDataBaseSql
  80. {
  81. get
  82. {
  83. return "mysqldump.exe {0} -uroot -p > {1} ";
  84. }
  85. }
  86. protected override string CreateTableSql
  87. {
  88. get
  89. {
  90. return "CREATE STABLE IF NOT EXISTS {0}(\r\n{1} ) TAGS(" + SqlBuilder.GetTranslationColumnName("TagsTypeId") + " VARCHAR(20))";
  91. }
  92. }
  93. protected override string CreateTableColumn
  94. {
  95. get
  96. {
  97. return "{0} {1}{2} {3} {4} {5}";
  98. }
  99. }
  100. protected override string TruncateTableSql
  101. {
  102. get
  103. {
  104. return "TRUNCATE TABLE {0}";
  105. }
  106. }
  107. protected override string BackupTableSql
  108. {
  109. get
  110. {
  111. return "create table {0} as (select * from {1} limit {2} offset 0)";
  112. }
  113. }
  114. protected override string DropTableSql
  115. {
  116. get
  117. {
  118. return "DROP TABLE {0}";
  119. }
  120. }
  121. protected override string DropColumnToTableSql
  122. {
  123. get
  124. {
  125. return "ALTER TABLE {0} DROP COLUMN {1}";
  126. }
  127. }
  128. protected override string DropConstraintSql
  129. {
  130. get
  131. {
  132. return "ALTER TABLE {0} DROP CONSTRAINT {1}";
  133. }
  134. }
  135. protected override string RenameColumnSql
  136. {
  137. get
  138. {
  139. return "ALTER TABLE {0} RENAME {1} TO {2}";
  140. }
  141. }
  142. protected override string AddColumnRemarkSql => "comment on column {1}.{0} is '{2}'";
  143. protected override string DeleteColumnRemarkSql => "comment on column {1}.{0} is ''";
  144. protected override string IsAnyColumnRemarkSql
  145. { get { throw new NotSupportedException(); } }
  146. protected override string AddTableRemarkSql => "comment on table {0} is '{1}'";
  147. protected override string DeleteTableRemarkSql => "comment on table {0} is ''";
  148. protected override string IsAnyTableRemarkSql
  149. { get { throw new NotSupportedException(); } }
  150. protected override string RenameTableSql => "alter table {0} to {1}";
  151. protected override string CreateIndexSql
  152. {
  153. get
  154. {
  155. return "CREATE {3} INDEX Index_{0}_{2} ON {0} ({1})";
  156. }
  157. }
  158. protected override string AddDefaultValueSql
  159. {
  160. get
  161. {
  162. return "ALTER TABLE {0} ALTER COLUMN {1} SET DEFAULT {2}";
  163. }
  164. }
  165. protected override string IsAnyIndexSql
  166. {
  167. get
  168. {
  169. return " SELECT count(1) WHERE upper('{0}') IN ( SELECT upper(indexname) FROM pg_indexes )";
  170. }
  171. }
  172. protected override string IsAnyProcedureSql => throw new NotImplementedException();
  173. #endregion DDL
  174. #region Check
  175. protected override string CheckSystemTablePermissionsSql
  176. {
  177. get
  178. {
  179. return "SHOW DATABASES";
  180. }
  181. }
  182. #endregion Check
  183. #region Scattered
  184. protected override string CreateTableNull
  185. {
  186. get
  187. {
  188. return " ";
  189. }
  190. }
  191. protected override string CreateTableNotNull
  192. {
  193. get
  194. {
  195. return " ";
  196. }
  197. }
  198. protected override string CreateTablePirmaryKey
  199. {
  200. get
  201. {
  202. return "PRIMARY KEY";
  203. }
  204. }
  205. protected override string CreateTableIdentity
  206. {
  207. get
  208. {
  209. return "serial";
  210. }
  211. }
  212. #endregion Scattered
  213. #region Methods
  214. public override bool AddColumn(string tableName, DbColumnInfo columnInfo)
  215. {
  216. if (columnInfo.DbColumnName == "TagsTypeId")
  217. {
  218. return true;
  219. }
  220. tableName = SqlBuilder.GetTranslationTableName(tableName);
  221. var isAddNotNUll = columnInfo.IsNullable == false && columnInfo.DefaultValue.HasValue();
  222. if (isAddNotNUll)
  223. {
  224. columnInfo = Context.Utilities.TranslateCopy(columnInfo);
  225. columnInfo.IsNullable = true;
  226. }
  227. string sql = GetAddColumnSql(tableName, columnInfo);
  228. Context.Ado.ExecuteCommand(sql);
  229. return true;
  230. }
  231. public override List<DbTableInfo> GetViewInfoList(bool isCache = true)
  232. {
  233. return new List<DbTableInfo>();
  234. }
  235. public override bool CreateDatabase(string databaseName, string databaseDirectory = null)
  236. {
  237. var db = Context.CopyNew();
  238. db.Ado.Connection.ChangeDatabase("");
  239. var sql = CreateDataBaseSql;
  240. if (Context.CurrentConnectionConfig.ConnectionString.ToLower().Contains("config_us"))
  241. {
  242. sql += " PRECISION 'us'";
  243. }
  244. else if (Context.CurrentConnectionConfig.ConnectionString.ToLower().Contains("config_ns"))
  245. {
  246. sql += " PRECISION 'ns'";
  247. }
  248. db.Ado.ExecuteCommand(string.Format(sql, databaseName));
  249. return true;
  250. }
  251. public override List<string> GetIndexList(string tableName)
  252. {
  253. var sql = $"SELECT indexname, indexdef FROM pg_indexes WHERE upper(tablename) = upper('{tableName}')";
  254. return Context.Ado.SqlQuery<string>(sql);
  255. }
  256. public override List<string> GetProcList(string dbName)
  257. {
  258. var sql = $"SELECT proname FROM pg_proc p JOIN pg_namespace n ON p.pronamespace = n.oid WHERE n.nspname = '{dbName}'";
  259. return Context.Ado.SqlQuery<string>(sql);
  260. }
  261. public override bool AddDefaultValue(string tableName, string columnName, string defaultValue)
  262. {
  263. return base.AddDefaultValue(SqlBuilder.GetTranslationTableName(tableName), SqlBuilder.GetTranslationTableName(columnName), defaultValue);
  264. }
  265. public override bool AddColumnRemark(string columnName, string tableName, string description)
  266. {
  267. tableName = SqlBuilder.GetTranslationTableName(tableName);
  268. string sql = string.Format(AddColumnRemarkSql, SqlBuilder.GetTranslationColumnName(columnName.ToLower(isAutoToLowerCodeFirst)), tableName, "");
  269. //Context.Ado.ExecuteCommand(sql);
  270. return false;
  271. }
  272. public override bool AddTableRemark(string tableName, string description)
  273. {
  274. tableName = SqlBuilder.GetTranslationTableName(tableName);
  275. return base.AddTableRemark(tableName, description);
  276. }
  277. public override bool UpdateColumn(string tableName, DbColumnInfo columnInfo)
  278. {
  279. tableName = SqlBuilder.GetTranslationTableName(tableName);
  280. var columnName = SqlBuilder.GetTranslationColumnName(columnInfo.DbColumnName);
  281. string sql = GetUpdateColumnSql(tableName, columnInfo);
  282. Context.Ado.ExecuteCommand(sql);
  283. var isnull = columnInfo.IsNullable ? " DROP NOT NULL " : " SET NOT NULL ";
  284. Context.Ado.ExecuteCommand(string.Format("alter table {0} alter {1} {2}", tableName, columnName, isnull));
  285. return true;
  286. }
  287. protected override string GetUpdateColumnSql(string tableName, DbColumnInfo columnInfo)
  288. {
  289. string columnName = SqlBuilder.GetTranslationColumnName(columnInfo.DbColumnName);
  290. tableName = SqlBuilder.GetTranslationTableName(tableName);
  291. string dataSize = GetSize(columnInfo);
  292. string dataType = columnInfo.DataType;
  293. //if (!string.IsNullOrEmpty(dataType))
  294. //{
  295. // dataType = " type " + dataType;
  296. //}
  297. string nullType = "";
  298. string primaryKey = null;
  299. string identity = null;
  300. string result = string.Format(AlterColumnToTableSql, tableName, columnName, dataType, dataSize, nullType, primaryKey, identity);
  301. return result;
  302. }
  303. public override bool AddRemark(EntityInfo entity)
  304. {
  305. var db = Context;
  306. var columns = entity.Columns.Where(it => it.IsIgnore == false).ToList();
  307. foreach (var item in columns)
  308. {
  309. if (item.ColumnDescription != null)
  310. {
  311. db.DbMaintenance.AddColumnRemark(item.DbColumnName, item.DbTableName, item.ColumnDescription);
  312. }
  313. }
  314. //table remak
  315. if (entity.TableDescription != null)
  316. {
  317. db.DbMaintenance.AddTableRemark(entity.DbTableName, entity.TableDescription);
  318. }
  319. return true;
  320. }
  321. public override bool CreateTable(string tableName, List<DbColumnInfo> columns, bool isCreatePrimaryKey = true)
  322. {
  323. if (columns.HasValue())
  324. {
  325. foreach (var item in columns)
  326. {
  327. if (item.DbColumnName != null && item.DbColumnName.Equals("GUID", StringComparison.CurrentCultureIgnoreCase) && item.Length == 0)
  328. {
  329. item.Length = 10;
  330. }
  331. }
  332. }
  333. string sql = GetCreateTableSql(tableName, columns);
  334. string primaryKeyInfo = null;
  335. if (columns.Any(it => it.IsPrimarykey) && isCreatePrimaryKey)
  336. {
  337. primaryKeyInfo = string.Format(", Primary key({0})", string.Join(",", columns.Where(it => it.IsPrimarykey).Select(it => SqlBuilder.GetTranslationColumnName(it.DbColumnName.ToLower(isAutoToLowerCodeFirst)))));
  338. }
  339. sql = sql.Replace("$PrimaryKey", primaryKeyInfo);
  340. Context.Ado.ExecuteCommand(sql);
  341. return true;
  342. }
  343. protected override string GetCreateTableSql(string tableName, List<DbColumnInfo> columns)
  344. {
  345. List<string> columnArray = new List<string>();
  346. Check.Exception(columns.IsNullOrEmpty(), "No columns found ");
  347. foreach (var item in columns.Where(x => x.DbColumnName != null))
  348. {
  349. string columnName = item.DbColumnName;
  350. string dataType = item.DataType;
  351. if (dataType == "varchar" && item.Length == 0)
  352. {
  353. item.Length = 1;
  354. }
  355. //if (dataType == "uuid")
  356. //{
  357. // item.Length = 50;
  358. // dataType = "varchar";
  359. //}
  360. string dataSize = item.Length > 0 ? string.Format("({0})", item.Length) : null;
  361. //if (item.DecimalDigits > 0&&item.Length>0 && dataType?.ToLower()== "float")
  362. //{
  363. // item.Length = 0;
  364. // dataSize = $"({item.Length},{item.DecimalDigits})";
  365. //}
  366. //if (item.DecimalDigits > 0 && item.Length > 0 && dataType?.ToLower() == "double")
  367. //{
  368. // dataSize = $"({item.Length},{item.DecimalDigits})";
  369. //}
  370. //if (item.DecimalDigits > 0 && item.Length > 0 && dataType?.ToLower() == "decimal")
  371. //{
  372. // dataSize = $"({item.Length},{item.DecimalDigits})";
  373. //}
  374. //if (item.DecimalDigits == 0 && item.Length == 0 && dataType?.ToLower() == "float")
  375. //{
  376. // dataType = $"FLOAT(18,4)";
  377. //}
  378. //if (item.DecimalDigits == 0 && item.Length == 0 && dataType?.ToLower() == "double")
  379. //{
  380. // dataType = $"DOUBLE(18,4)";
  381. //}
  382. if (item.Length == 0 && dataType?.ToLower()?.IsIn("nchar", "varchar") == true)
  383. {
  384. dataType = "VARCHAR(200)";
  385. }
  386. if (dataType?.ToLower()?.IsIn("float", "double") == true)
  387. {
  388. dataSize = null;
  389. }
  390. string primaryKey = null;
  391. string addItem = string.Format(CreateTableColumn, SqlBuilder.GetTranslationColumnName(columnName.ToLower(isAutoToLowerCodeFirst)), dataType, dataSize, null, primaryKey, "");
  392. columnArray.Add(addItem);
  393. }
  394. string tableString = string.Format(CreateTableSql, SqlBuilder.GetTranslationTableName(tableName.ToLower(isAutoToLowerCodeFirst)), string.Join(",\r\n", columnArray));
  395. var childTableName = SqlBuilder.GetTranslationTableName(tableName.ToLower(isAutoToLowerCodeFirst));
  396. var stableName = SqlBuilder.GetTranslationTableName(tableName.ToLower(isAutoToLowerCodeFirst));
  397. //Context.Ado.ExecuteCommand(tableString);
  398. //var createChildSql = $"CREATE TABLE IF NOT EXISTS {childTableName} USING {stableName} TAGS('default')";
  399. //Context.Ado.ExecuteCommand(createChildSql);
  400. return tableString;
  401. }
  402. public override bool IsAnyConstraint(string constraintName)
  403. {
  404. throw new NotSupportedException("PgSql IsAnyConstraint NotSupportedException");
  405. }
  406. public override bool BackupDataBase(string databaseName, string fullFileName)
  407. {
  408. Check.ThrowNotSupportedException("PgSql BackupDataBase NotSupported");
  409. return false;
  410. }
  411. public override List<DbColumnInfo> GetColumnInfosByTableName(string tableName, bool isCache = true)
  412. {
  413. var sql = $"select * from {SqlBuilder.GetTranslationColumnName(tableName)} where 1=2 ";
  414. List<DbColumnInfo> result = new List<DbColumnInfo>();
  415. DataTable dt = null;
  416. try
  417. {
  418. dt = Context.Ado.GetDataTable(sql);
  419. }
  420. catch (Exception)
  421. {
  422. sql = $"select * from `{tableName}` where 1=2 ";
  423. dt = Context.Ado.GetDataTable(sql);
  424. }
  425. foreach (DataColumn item in dt.Columns)
  426. {
  427. var addItem = new DbColumnInfo()
  428. {
  429. DbColumnName = item.ColumnName,
  430. DataType = item.DataType.Name
  431. };
  432. result.Add(addItem);
  433. }
  434. if (result.Count(it => it.DataType == "DateTime") == 1)
  435. {
  436. result.First(it => it.DataType == "DateTime").IsPrimarykey = true;
  437. }
  438. return result;
  439. }
  440. #endregion Methods
  441. #region Helper
  442. private bool isAutoToLowerCodeFirst
  443. {
  444. get
  445. {
  446. if (Context.CurrentConnectionConfig.MoreSettings == null) return true;
  447. else if (
  448. Context.CurrentConnectionConfig.MoreSettings.PgSqlIsAutoToLower == false &&
  449. Context.CurrentConnectionConfig.MoreSettings?.PgSqlIsAutoToLowerCodeFirst == false)
  450. {
  451. return false;
  452. }
  453. else
  454. {
  455. return true;
  456. }
  457. }
  458. }
  459. private string GetSchema()
  460. {
  461. var schema = "public";
  462. if (System.Text.RegularExpressions.Regex.IsMatch(Context.CurrentConnectionConfig.ConnectionString.ToLower(), "searchpath="))
  463. {
  464. var regValue = System.Text.RegularExpressions.Regex.Match(Context.CurrentConnectionConfig.ConnectionString.ToLower(), @"searchpath\=(\w+)").Groups[1].Value;
  465. if (regValue.HasValue())
  466. {
  467. schema = regValue;
  468. }
  469. }
  470. else if (System.Text.RegularExpressions.Regex.IsMatch(Context.CurrentConnectionConfig.ConnectionString.ToLower(), "search path="))
  471. {
  472. var regValue = System.Text.RegularExpressions.Regex.Match(Context.CurrentConnectionConfig.ConnectionString.ToLower(), @"search path\=(\w+)").Groups[1].Value;
  473. if (regValue.HasValue())
  474. {
  475. schema = regValue;
  476. }
  477. }
  478. return schema;
  479. }
  480. private DataTable GetTables()
  481. {
  482. return Context.Ado.GetDataTable("SHOW TABLES");
  483. }
  484. private DataTable GetSTables()
  485. {
  486. return Context.Ado.GetDataTable("SHOW STABLES");
  487. }
  488. #endregion Helper
  489. }
  490. }