QuestDBDbMaintenance.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. namespace SqlSugar
  7. {
  8. public class QuestDBDbMaintenance : DbMaintenanceProvider
  9. {
  10. #region DML
  11. protected override string GetDataBaseSql
  12. {
  13. get
  14. {
  15. return CreateDataBaseSql;
  16. }
  17. }
  18. protected override string GetColumnInfosByTableNameSql
  19. {
  20. get
  21. {
  22. string schema = GetSchema();
  23. string sql = @"SHOW COLUMNS FROM {0}";
  24. return sql;
  25. }
  26. }
  27. protected override string GetTableInfoListSql
  28. {
  29. get
  30. {
  31. var schema = GetSchema();
  32. return @"SHOW TABLES";
  33. }
  34. }
  35. protected override string GetViewInfoListSql
  36. {
  37. get
  38. {
  39. return "select * from (select 1 as id) t where id=0";
  40. }
  41. }
  42. #endregion
  43. #region DDL
  44. protected override string CreateDataBaseSql
  45. {
  46. get
  47. {
  48. return "select * from (select 1 as id) t where id=0";
  49. }
  50. }
  51. protected override string AddPrimaryKeySql
  52. {
  53. get
  54. {
  55. return "";
  56. }
  57. }
  58. protected override string AddColumnToTableSql
  59. {
  60. get
  61. {
  62. return "ALTER TABLE {0} ADD COLUMN {1} {2}";
  63. }
  64. }
  65. protected override string AlterColumnToTableSql
  66. {
  67. get
  68. {
  69. throw new NotSupportedException("Alter Column ");
  70. }
  71. }
  72. protected override string BackupDataBaseSql
  73. {
  74. get
  75. {
  76. return "BACKUP DATABASE";
  77. }
  78. }
  79. protected override string CreateTableSql
  80. {
  81. get
  82. {
  83. return "CREATE TABLE {0}(\r\n{1})";
  84. }
  85. }
  86. protected override string CreateTableColumn
  87. {
  88. get
  89. {
  90. return "{0} {1}{2} {3} {4} {5}";
  91. }
  92. }
  93. protected override string TruncateTableSql
  94. {
  95. get
  96. {
  97. return "TRUNCATE TABLE {0}";
  98. }
  99. }
  100. protected override string BackupTableSql
  101. {
  102. get
  103. {
  104. return "create table {0} as (select * from {1} limit {2} offset 0)";
  105. }
  106. }
  107. protected override string DropTableSql
  108. {
  109. get
  110. {
  111. return "DROP TABLE {0}";
  112. }
  113. }
  114. protected override string DropColumnToTableSql
  115. {
  116. get
  117. {
  118. return "ALTER TABLE {0} DROP COLUMN {1}";
  119. }
  120. }
  121. protected override string DropConstraintSql
  122. {
  123. get
  124. {
  125. return " ";
  126. }
  127. }
  128. protected override string RenameColumnSql
  129. {
  130. get
  131. {
  132. return "ALTER TABLE {0} RENAME COLUMN {1} TO {2}";
  133. }
  134. }
  135. protected override string AddColumnRemarkSql => " ";
  136. protected override string DeleteColumnRemarkSql => " ";
  137. protected override string IsAnyColumnRemarkSql { get { throw new NotSupportedException(); } }
  138. protected override string AddTableRemarkSql => " ";
  139. protected override string DeleteTableRemarkSql => " ";
  140. protected override string IsAnyTableRemarkSql { get { throw new NotSupportedException(); } }
  141. protected override string RenameTableSql => "alter table 表名 {0} to {1}";
  142. protected override string CreateIndexSql
  143. {
  144. get
  145. {
  146. return "CREATE {3} INDEX Index_{0}_{2} ON {0} ({1})";
  147. }
  148. }
  149. protected override string AddDefaultValueSql
  150. {
  151. get
  152. {
  153. return "ALTER TABLE {0} ALTER COLUMN {1} SET DEFAULT {2}";
  154. }
  155. }
  156. protected override string IsAnyIndexSql
  157. {
  158. get
  159. {
  160. return " Select count(1) from (SELECT to_regclass('{0}') as c ) t where t.c is not null";
  161. }
  162. }
  163. protected override string IsAnyProcedureSql => throw new NotImplementedException();
  164. #endregion
  165. #region Check
  166. protected override string CheckSystemTablePermissionsSql
  167. {
  168. get
  169. {
  170. return "select 1 ";
  171. }
  172. }
  173. #endregion
  174. #region Scattered
  175. protected override string CreateTableNull
  176. {
  177. get
  178. {
  179. return "DEFAULT NULL";
  180. }
  181. }
  182. protected override string CreateTableNotNull
  183. {
  184. get
  185. {
  186. return "NOT NULL";
  187. }
  188. }
  189. protected override string CreateTablePirmaryKey
  190. {
  191. get
  192. {
  193. return "PRIMARY KEY";
  194. }
  195. }
  196. protected override string CreateTableIdentity
  197. {
  198. get
  199. {
  200. return "serial";
  201. }
  202. }
  203. #endregion
  204. #region Methods
  205. public override void AddIndex(EntityInfo entityInfo)
  206. {
  207. if (entityInfo.Indexs != null)
  208. {
  209. foreach (var item in entityInfo.Indexs)
  210. {
  211. CreateIndex(entityInfo.DbTableName, item.IndexFields.Select(it => it.Key).ToArray(),item.IsUnique);
  212. }
  213. }
  214. }
  215. public override bool CreateIndex(string tableName, string[] columnNames, bool isUnique = false)
  216. {
  217. if (isUnique)
  218. {
  219. this.Context.Ado.ExecuteCommand($"ALTER TABLE {tableName} DEDUP ENABLE UPSERT KEYS({string.Join(",",columnNames)})");
  220. return true;
  221. }
  222. var columnInfos = this.Context.Ado.SqlQuery<QuestDbColumn>("SHOW COLUMNS FROM '" + tableName + "'");
  223. foreach (var columnInfo in columnInfos)
  224. {
  225. if (columnNames.Any(z => z.EqualCase(columnInfo.Column)))
  226. {
  227. if (!columnInfo.Type.EqualCase("SYMBOL"))
  228. {
  229. Check.ExceptionEasy(true, "Only the SYMBOL type can be indexed", $"字段{columnInfo.Column} 不是SYMBOL并且实体是string才能添加索引,CodeFirst需要指定类型: SYMBOL");
  230. }
  231. if (columnInfo.Indexed == false)
  232. {
  233. var indexSql = $"ALTER TABLE '{tableName}' ALTER COLUMN {columnInfo.Column} ADD INDEX ";
  234. this.Context.Ado.ExecuteCommand(indexSql);
  235. }
  236. }
  237. }
  238. return true;
  239. }
  240. public override bool CreateIndex(string tableName, string[] columnNames, string IndexName, bool isUnique = false)
  241. {
  242. if(isUnique)
  243. throw new Exception("no support unique index");
  244. return CreateIndex(tableName, columnNames, isUnique);
  245. }
  246. public override bool CreateUniqueIndex(string tableName, string[] columnNames)
  247. {
  248. throw new Exception("no support unique index");
  249. }
  250. public override bool IsAnyIndex(string indexName)
  251. {
  252. return false;
  253. }
  254. public override List<DbTableInfo> GetTableInfoList(bool isCache = true)
  255. {
  256. var dt = this.Context.Ado.GetDataTable(GetTableInfoListSql);
  257. List<DbTableInfo> result = new List<DbTableInfo>();
  258. foreach (System.Data.DataRow dr in dt.Rows)
  259. {
  260. DbTableInfo di = new DbTableInfo();
  261. di.Name = dr[0] + "";
  262. if (!di.Name.Contains("sys.") && !di.Name.IsIn("telemetry", "telemetry_config") )
  263. {
  264. result.Add(di);
  265. }
  266. }
  267. return result;
  268. }
  269. public override bool AddDefaultValue(string tableName, string columnName, string defaultValue)
  270. {
  271. return base.AddDefaultValue(this.SqlBuilder.GetTranslationTableName(tableName), this.SqlBuilder.GetTranslationTableName(columnName), defaultValue);
  272. }
  273. public override bool AddColumnRemark(string columnName, string tableName, string description)
  274. {
  275. //tableName = this.SqlBuilder.GetTranslationTableName(tableName);
  276. //string sql = string.Format(this.AddColumnRemarkSql, columnName, tableName, description);
  277. //this.Context.Ado.ExecuteCommand(sql);
  278. return true;
  279. }
  280. public override bool AddTableRemark(string tableName, string description)
  281. {
  282. //tableName = this.SqlBuilder.GetTranslationTableName(tableName);
  283. //return base.AddTableRemark(tableName, description);
  284. return true;
  285. }
  286. public override bool UpdateColumn(string tableName, DbColumnInfo columnInfo)
  287. {
  288. //no support
  289. return false;
  290. }
  291. public override bool AddPrimaryKey(string tableName, string columnName)
  292. {
  293. return true;
  294. }
  295. //protected override string GetUpdateColumnSql(string tableName, DbColumnInfo columnInfo)
  296. //{
  297. // string columnName = this.SqlBuilder.GetTranslationColumnName(columnInfo.DbColumnName);
  298. // tableName = this.SqlBuilder.GetTranslationTableName(tableName);
  299. // string dataSize = GetSize(columnInfo);
  300. // string dataType = columnInfo.DataType;
  301. // if (!string.IsNullOrEmpty(dataType))
  302. // {
  303. // dataType = " type " + dataType;
  304. // }
  305. // string nullType = "";
  306. // string primaryKey = null;
  307. // string identity = null;
  308. // string result = string.Format(this., tableName, columnName, dataType, dataSize, nullType, primaryKey, identity);
  309. // return result;
  310. //}
  311. /// <summary>
  312. ///by current connection string
  313. /// </summary>
  314. /// <param name="databaseDirectory"></param>
  315. /// <returns></returns>
  316. public override bool CreateDatabase(string databaseName, string databaseDirectory = null)
  317. {
  318. if (databaseDirectory != null)
  319. {
  320. if (!FileHelper.IsExistDirectory(databaseDirectory))
  321. {
  322. FileHelper.CreateDirectory(databaseDirectory);
  323. }
  324. }
  325. var oldDatabaseName = this.Context.Ado.Connection.Database;
  326. var connection = this.Context.CurrentConnectionConfig.ConnectionString;
  327. connection = connection.Replace(oldDatabaseName, "postgres");
  328. var newDb = new SqlSugarClient(new ConnectionConfig()
  329. {
  330. DbType = this.Context.CurrentConnectionConfig.DbType,
  331. IsAutoCloseConnection = true,
  332. ConnectionString = connection
  333. });
  334. if (!GetDataBaseList(newDb).Any(it => it.Equals(databaseName, StringComparison.CurrentCultureIgnoreCase)))
  335. {
  336. newDb.Ado.ExecuteCommand(string.Format(CreateDataBaseSql, this.SqlBuilder.SqlTranslationLeft+databaseName+this.SqlBuilder.SqlTranslationRight, databaseDirectory));
  337. }
  338. return true;
  339. }
  340. public override bool AddRemark(EntityInfo entity)
  341. {
  342. var db = this.Context;
  343. var columns = entity.Columns.Where(it => it.IsIgnore == false).ToList();
  344. foreach (var item in columns)
  345. {
  346. if (item.ColumnDescription != null)
  347. {
  348. db.DbMaintenance.AddColumnRemark(item.DbColumnName, item.DbTableName, item.ColumnDescription);
  349. }
  350. }
  351. //table remak
  352. if (entity.TableDescription != null)
  353. {
  354. db.DbMaintenance.AddTableRemark(entity.DbTableName, entity.TableDescription);
  355. }
  356. return true;
  357. }
  358. public override bool CreateTable(string tableName, List<DbColumnInfo> columns, bool isCreatePrimaryKey = true)
  359. {
  360. var splitSql = "";
  361. if (tableName.Contains("_TIMESTAMP("))
  362. {
  363. splitSql = Regex.Match(tableName,@"_TIMESTAMP\(.+$").Value;
  364. tableName = tableName.Replace(splitSql, "");
  365. }
  366. if (columns.HasValue())
  367. {
  368. foreach (var item in columns)
  369. {
  370. if (item.DbColumnName.Equals("GUID", StringComparison.CurrentCultureIgnoreCase) && item.Length == 0)
  371. {
  372. item.Length = 10;
  373. }
  374. }
  375. }
  376. string sql = GetCreateTableSql(tableName, columns);
  377. string primaryKeyInfo = null;
  378. if (columns.Any(it => it.IsPrimarykey) && isCreatePrimaryKey)
  379. {
  380. primaryKeyInfo = string.Format(", Primary key({0})", string.Join(",", columns.Where(it => it.IsPrimarykey).Select(it => this.SqlBuilder.GetTranslationColumnName(it.DbColumnName.ToLower()))));
  381. }
  382. sql = sql.Replace("$PrimaryKey", primaryKeyInfo);
  383. this.Context.Ado.ExecuteCommand(sql+ splitSql.TrimStart('_')+ " BYPASS WAL");
  384. return true;
  385. }
  386. protected override string GetCreateTableSql(string tableName, List<DbColumnInfo> columns)
  387. {
  388. List<string> columnArray = new List<string>();
  389. Check.Exception(columns.IsNullOrEmpty(), "No columns found ");
  390. foreach (var item in columns)
  391. {
  392. string columnName = item.DbColumnName;
  393. string dataType = item.DataType;
  394. //if (dataType == "varchar" && item.Length == 0)
  395. //{
  396. // item.Length = 1;
  397. //}
  398. //if (dataType == "uuid")
  399. //{
  400. // item.Length = 50;
  401. // dataType = "varchar";
  402. //}
  403. string dataSize = "";
  404. //if (item.DecimalDigits > 0&&item.Length>0 && dataType == "numeric")
  405. //{
  406. // dataSize = $"({item.Length},{item.DecimalDigits})";
  407. //}
  408. string nullType = "";
  409. string primaryKey = null;
  410. string addItem = string.Format(this.CreateTableColumn, this.SqlBuilder.GetTranslationColumnName(columnName.ToLower()), dataType, dataSize, nullType, primaryKey, "");
  411. //if (item.IsIdentity)
  412. //{
  413. // string length = dataType.Substring(dataType.Length - 1);
  414. // string identityDataType = "serial" + length;
  415. // addItem = addItem.Replace(dataType, identityDataType);
  416. //}
  417. columnArray.Add(addItem);
  418. }
  419. string tableString = string.Format(this.CreateTableSql, this.SqlBuilder.GetTranslationTableName(tableName), string.Join(",\r\n", columnArray));
  420. return tableString;
  421. }
  422. public override bool IsAnyConstraint(string constraintName)
  423. {
  424. throw new NotSupportedException("PgSql IsAnyConstraint NotSupportedException");
  425. }
  426. public override bool BackupDataBase(string databaseName, string fullFileName)
  427. {
  428. Check.ThrowNotSupportedException("PgSql BackupDataBase NotSupported");
  429. return false;
  430. }
  431. public override List<DbColumnInfo> GetColumnInfosByTableName(string tableName, bool isCache = true)
  432. {
  433. var sql = String.Format(GetColumnInfosByTableNameSql,tableName);
  434. List<DbColumnInfo> result = new List<DbColumnInfo>();
  435. var dt = this.Context.Ado.GetDataTable(sql);
  436. foreach (System.Data.DataRow column in dt.Rows)
  437. {
  438. DbColumnInfo dbColumnInfo = new DbColumnInfo();
  439. dbColumnInfo.DbColumnName = column[0]+"";
  440. dbColumnInfo.DataType = column[1]+"";
  441. result.Add(dbColumnInfo);
  442. }
  443. return result;
  444. }
  445. #endregion
  446. #region Helper
  447. private string GetSchema()
  448. {
  449. var schema = "public";
  450. if (System.Text.RegularExpressions.Regex.IsMatch(this.Context.CurrentConnectionConfig.ConnectionString.ToLower(), "searchpath="))
  451. {
  452. var regValue = System.Text.RegularExpressions.Regex.Match(this.Context.CurrentConnectionConfig.ConnectionString.ToLower(), @"searchpath\=(\w+)").Groups[1].Value;
  453. if (regValue.HasValue())
  454. {
  455. schema = regValue;
  456. }
  457. }
  458. else if (System.Text.RegularExpressions.Regex.IsMatch(this.Context.CurrentConnectionConfig.ConnectionString.ToLower(), "search path="))
  459. {
  460. var regValue = System.Text.RegularExpressions.Regex.Match(this.Context.CurrentConnectionConfig.ConnectionString.ToLower(), @"search path\=(\w+)").Groups[1].Value;
  461. if (regValue.HasValue())
  462. {
  463. schema = regValue;
  464. }
  465. }
  466. return schema;
  467. }
  468. #endregion
  469. #region HelperClass
  470. internal class QuestDbColumn
  471. {
  472. public string Column { get; set; }
  473. public string Type { get; set; }
  474. public bool Indexed { get; set; }
  475. }
  476. #endregion
  477. }
  478. }