AzureCosmosExOld.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. //using Azure;
  2. //using Azure.Cosmos;
  3. //using System;
  4. //using System.Collections.Generic;
  5. //using System.Diagnostics;
  6. //using System.IO;
  7. //using System.Linq;
  8. //using System.Text;
  9. //using System.Text.Json;
  10. //using System.Threading.Tasks;
  11. //using TEAMModelOS.SDK.Context.Exception;
  12. //using TEAMModelOS.SDK.Models;
  13. //namespace TEAMModelOS.SDK.DI.AzureCosmos.Inner
  14. //{
  15. // public static class AzureCosmosExOld
  16. // {
  17. // /// <summary>
  18. // /// 缓存前缀
  19. // /// </summary>
  20. // private const string CacheCosmosPrefix = "cosmos:";
  21. // /// <summary>
  22. // /// ttl时长 1秒
  23. // /// </summary>
  24. // private const int ttl = 1;
  25. // /// <summary>
  26. // /// 分页大小
  27. // /// </summary>
  28. // private const int pageSize = 200;
  29. // /// <summary>
  30. // /// 超时时间
  31. // /// </summary>
  32. // private const int timeoutSeconds = 86400;
  33. // // TODO 此区需移除或优化
  34. // #region 此区需移除或优化
  35. // public static async Task<T> SaveOrUpdate<T>(this AzureCosmosFactory azureCosmosFactory, T entity) where T : CosmosEntity
  36. // {
  37. // AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
  38. // entity.pk = container.type.Name;
  39. // ItemResponse<T> response = await container.container.UpsertItemAsync(item: entity);
  40. // if (container.cache && RedisHelper.Instance != null)
  41. // {
  42. // if (!RedisHelper.Exists(CacheCosmosPrefix + container.container.Id))
  43. // {
  44. // await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, entity.id, entity);
  45. // }
  46. // else
  47. // {
  48. // await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, entity.id, entity);
  49. // await RedisHelper.ExpireAsync(CacheCosmosPrefix + container.container.Id, timeoutSeconds);
  50. // }
  51. // }
  52. // return response.Value;
  53. // }
  54. // public static async Task<List<T>> SaveOrUpdateAll<T>(this AzureCosmosFactory azureCosmosFactory, List<T> enyites) where T : CosmosEntity
  55. // {
  56. // Type type = typeof(T);
  57. // int pages = (int)Math.Ceiling((double)enyites.Count / pageSize);
  58. // AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
  59. // bool flag = false;
  60. // if (RedisHelper.Exists(CacheCosmosPrefix + container.container.Id))
  61. // {
  62. // flag = true;
  63. // }
  64. // string partitionKey = AzureCosmosUtil.GetPartitionKey(type);
  65. // Stopwatch stopwatch = Stopwatch.StartNew();
  66. // for (int i = 0; i < pages; i++)
  67. // {
  68. // List<T> lists = enyites.Skip((i) * pageSize).Take(pageSize).ToList();
  69. // List<KeyValuePair<PartitionKey, Stream>> itemsToInsert = new List<KeyValuePair<PartitionKey, Stream>>();
  70. // lists.ForEach(async x =>
  71. // {
  72. // x.pk = type.Name;
  73. // MemoryStream stream = new MemoryStream();
  74. // await JsonSerializer.SerializeAsync(stream, x, new JsonSerializerOptions { IgnoreNullValues = true });
  75. // object o = type.GetProperty(partitionKey).GetValue(x, null);
  76. // KeyValuePair<PartitionKey, Stream> keyValue = new KeyValuePair<PartitionKey, Stream>(new PartitionKey(o.ToString()), stream);
  77. // itemsToInsert.Add(keyValue);
  78. // });
  79. // List<Task> tasks = new List<Task>(lists.Count);
  80. // itemsToInsert.ForEach(item =>
  81. // {
  82. // tasks.Add(container.container.UpsertItemStreamAsync(item.Value, item.Key)
  83. // .ContinueWith((Task<Response> task) =>
  84. // {
  85. // }
  86. // ));
  87. // });
  88. // await Task.WhenAll(tasks);
  89. // if (container.cache && RedisHelper.Instance != null)
  90. // {
  91. // lists.ForEach(async x => {
  92. // await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, x.id, x);
  93. // });
  94. // }
  95. // }
  96. // if (container.cache && RedisHelper.Instance != null && !flag)
  97. // {
  98. // await RedisHelper.ExpireAsync(CacheCosmosPrefix + container.container.Id, timeoutSeconds);
  99. // }
  100. // stopwatch.Stop();
  101. // return enyites;
  102. // }
  103. // public static async Task<List<int>> FindCountByDict<T>(this AzureCosmosFactory azureCosmosFactory, Dictionary<string, object> dict)
  104. // {
  105. // Type type = typeof(T);
  106. // AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
  107. // string pk = type.Name;
  108. // StringBuilder sql = new StringBuilder("select value count(c) from c");
  109. // AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql, pk);
  110. // if (cosmosDbQuery == null)
  111. // {
  112. // return new List<int> { 0 };
  113. // }
  114. // QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
  115. // AsyncPageable<int> query = container.container.GetItemQueryIterator<int>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryRequestOptions);
  116. // return await ResultsFromFeedIterator(query);
  117. // }
  118. // public static async Task<List<dynamic>> FindCountByDict(this AzureCosmosFactory azureCosmosFactory, string CollectionName, Dictionary<string, object> dict)
  119. // {
  120. // if (azureCosmosFactory.CosmosDict.typeCosmos.TryGetValue(CollectionName, out AzureCosmosModel container))
  121. // {
  122. // string pk = container.type.Name;
  123. // dict.Remove("@CURRPAGE");
  124. // dict.Remove("@PAGESIZE");
  125. // dict.Remove("@ASC");
  126. // dict.Remove("@DESC");
  127. // StringBuilder sql = new StringBuilder("select value count(c) from c");
  128. // AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql, pk);
  129. // if (cosmosDbQuery == null)
  130. // {
  131. // return new List<dynamic> { 0 };
  132. // }
  133. // QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
  134. // AsyncPageable<dynamic> query = container.container.GetItemQueryIterator<dynamic>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryRequestOptions);
  135. // return await ResultsFromFeedIterator(query);
  136. // }
  137. // else
  138. // {
  139. // throw new BizException("CollectionName named:" + CollectionName + " dose not exsit in Database!");
  140. // }
  141. // }
  142. // public static async Task<List<dynamic>> FindCountByDict(this AzureCosmosFactory azureCosmosFactory, string CollectionName, JsonElement json)
  143. // {
  144. // if (azureCosmosFactory.CosmosDict.typeCosmos.TryGetValue(CollectionName, out AzureCosmosModel container))
  145. // {
  146. // Dictionary<string, object> dict = new Dictionary<string, object>();
  147. // var emobj = json.EnumerateObject();
  148. // while (emobj.MoveNext())
  149. // {
  150. // if (emobj.Current.Name != "@CURRPAGE" ||
  151. // emobj.Current.Name != "@PAGESIZE" ||
  152. // emobj.Current.Name != "@ASC" ||
  153. // emobj.Current.Name != "@DESC")
  154. // {
  155. // dict[emobj.Current.Name] = emobj.Current.Value;
  156. // }
  157. // }
  158. // string pk = container.type.Name;
  159. // StringBuilder sql = new StringBuilder("select value count(c) from c");
  160. // AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql, pk);
  161. // if (cosmosDbQuery == null)
  162. // {
  163. // return new List<dynamic> { 0 };
  164. // }
  165. // QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
  166. // AsyncPageable<dynamic> query = container.container.GetItemQueryIterator<dynamic>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryRequestOptions);
  167. // return await ResultsFromFeedIterator(query);
  168. // }
  169. // else
  170. // {
  171. // throw new BizException("CollectionName named:" + CollectionName + " dose not exsit in Database!");
  172. // }
  173. // }
  174. // public static async Task<T> Update<T>(this AzureCosmosFactory azureCosmosFactory, T entity) where T : CosmosEntity
  175. // {
  176. // Type type = typeof(T);
  177. // AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
  178. // string partitionKey = AzureCosmosUtil.GetPartitionKey(type);
  179. // entity.pk = type.Name;
  180. // object o = type.GetProperty(partitionKey).GetValue(entity, null);
  181. // ItemResponse<T> response = await container.container.ReplaceItemAsync(entity, entity.id, new PartitionKey(o.ToString()));
  182. // if (container.cache && RedisHelper.Instance != null)
  183. // {
  184. // if (!RedisHelper.Exists(CacheCosmosPrefix + container.container.Id))
  185. // {
  186. // await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, entity.id, entity);
  187. // }
  188. // else
  189. // {
  190. // await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, entity.id, entity);
  191. // await RedisHelper.ExpireAsync(CacheCosmosPrefix + container.container.Id, timeoutSeconds);
  192. // }
  193. // }
  194. // return response.Value;
  195. // }
  196. // internal class Item
  197. // {
  198. // public string id { get; set; }
  199. // public string pk { get; set; }
  200. // public MemoryStream stream { get; set; }
  201. // }
  202. // public static async Task<List<T>> UpdateAll<T>(this AzureCosmosFactory azureCosmosFactory, List<T> enyites) where T : CosmosEntity
  203. // {
  204. // //await Task.Run(() => Parallel.ForEach(entities, new ParallelOptions { MaxDegreeOfParallelism = 2 }, (item) =>
  205. // //{
  206. // // Task.WaitAll(Update(item));
  207. // //}));
  208. // Type type = typeof(T);
  209. // int pages = (int)Math.Ceiling((double)enyites.Count / pageSize);
  210. // AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
  211. // bool flag = false;
  212. // if (RedisHelper.Exists(CacheCosmosPrefix + container.container.Id))
  213. // {
  214. // flag = true;
  215. // }
  216. // string partitionKey = AzureCosmosUtil.GetPartitionKey(type);
  217. // Stopwatch stopwatch = Stopwatch.StartNew();
  218. // for (int i = 0; i < pages; i++)
  219. // {
  220. // List<T> lists = enyites.Skip((i) * pageSize).Take(pageSize).ToList();
  221. // List<Item> itemsToInsert = new List<Item>();
  222. // lists.ForEach(async x =>
  223. // {
  224. // x.pk = type.Name;
  225. // MemoryStream stream = new MemoryStream();
  226. // await JsonSerializer.SerializeAsync(stream, x, new JsonSerializerOptions { IgnoreNullValues = true });
  227. // object o = type.GetProperty(partitionKey).GetValue(x, null);
  228. // Item keyValue = new Item { id = x.id, pk = o.ToString(), stream = stream };
  229. // itemsToInsert.Add(keyValue);
  230. // });
  231. // List<Task> tasks = new List<Task>(lists.Count);
  232. // itemsToInsert.ForEach(item =>
  233. // {
  234. // tasks.Add(container.container.ReplaceItemStreamAsync(item.stream, item.id, new PartitionKey(item.pk))
  235. // .ContinueWith((Task<Response> task) =>
  236. // {
  237. // //using (ResponseMessage response = task.Result)
  238. // //{
  239. // // if (!response.IsSuccessStatusCode)
  240. // // {
  241. // // }
  242. // //}
  243. // }
  244. // ));
  245. // });
  246. // await Task.WhenAll(tasks);
  247. // if (container.cache && RedisHelper.Instance != null)
  248. // {
  249. // lists.ForEach(async x => {
  250. // await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, x.id, x);
  251. // });
  252. // }
  253. // }
  254. // if (container.cache && RedisHelper.Instance != null && !flag)
  255. // {
  256. // await RedisHelper.ExpireAsync(CacheCosmosPrefix + container.container.Id, timeoutSeconds);
  257. // }
  258. // stopwatch.Stop();
  259. // return enyites;
  260. // }
  261. // public static async Task<List<T>> FindByDict<T>(this AzureCosmosFactory azureCosmosFactory, Dictionary<string, object> dict, List<string> propertys = null) where T : CosmosEntity
  262. // {
  263. // StringBuilder sql;
  264. // sql = SQLHelper.GetSQLSelect(propertys);
  265. // string pk = typeof(T).Name;
  266. // AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql, pk);
  267. // QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
  268. // return await ResultsFromQueryAndOptions<T>(azureCosmosFactory, cosmosDbQuery, queryRequestOptions);
  269. // }
  270. // public static async Task<List<T>> FindByDict<T>(this AzureCosmosFactory azureCosmosFactory, JsonElement jsonElement, List<string> propertys = null) where T : CosmosEntity
  271. // {
  272. // StringBuilder sql;
  273. // sql = SQLHelper.GetSQLSelect(propertys);
  274. // string pk = typeof(T).Name;
  275. // //Dictionary<string, object> dict = new Dictionary<string, object>();
  276. // /* var emobj = jsonElement.EnumerateObject();
  277. // while (emobj.MoveNext())
  278. // {
  279. // dict[emobj.Current.Name] = emobj.Current.Value;
  280. // }
  281. // //处理code
  282. // if (dict.TryGetValue("code", out object _))
  283. // {
  284. // dict.Remove("code");
  285. // }*/
  286. // AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(jsonElement, sql, pk);
  287. // QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
  288. // return await ResultsFromQueryAndOptions<T>(azureCosmosFactory, cosmosDbQuery, queryRequestOptions);
  289. // }
  290. // public static async Task<List<dynamic>> FindByDict(this AzureCosmosFactory azureCosmosFactory, string CollectionName, JsonElement json, List<string> propertys = null)
  291. // {
  292. // if (azureCosmosFactory.CosmosDict.typeCosmos.TryGetValue(CollectionName, out AzureCosmosModel container))
  293. // {
  294. // string pk = container.type.Name;
  295. // StringBuilder sql;
  296. // sql = SQLHelper.GetSQLSelect(propertys);
  297. // AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(json, sql, pk);
  298. // QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
  299. // AsyncPageable<dynamic> query = container.container.GetItemQueryIterator<dynamic>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryRequestOptions);
  300. // return await ResultsFromFeedIterator(query);
  301. // }
  302. // else
  303. // {
  304. // throw new BizException("CollectionName named:" + CollectionName + " dose not exsit in Database!");
  305. // }
  306. // }
  307. // public static async Task<List<dynamic>> FindByDict(this AzureCosmosFactory azureCosmosFactory, string CollectionName, Dictionary<string, object> dict, List<string> propertys = null)
  308. // {
  309. // if (azureCosmosFactory.CosmosDict.typeCosmos.TryGetValue(CollectionName, out AzureCosmosModel container))
  310. // {
  311. // string pk = container.type.Name;
  312. // StringBuilder sql;
  313. // sql = SQLHelper.GetSQLSelect(propertys);
  314. // AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql, pk);
  315. // QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
  316. // AsyncPageable<dynamic> query = container.container.GetItemQueryIterator<dynamic>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryRequestOptions);
  317. // return await ResultsFromFeedIterator(query);
  318. // }
  319. // else
  320. // {
  321. // throw new BizException("CollectionName named:" + CollectionName + " dose not exsit in Database!");
  322. // }
  323. // }
  324. // public static async Task<List<IdPk>> DeleteAll<T>(this AzureCosmosFactory azureCosmosFactory, List<IdPk> ids) where T : CosmosEntity
  325. // {
  326. // AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
  327. // List<IdPk> idPks = new List<IdPk>();
  328. // if (container.monitor)
  329. // {
  330. // List<T> list = await azureCosmosFactory.FindByDict<T>(new Dictionary<string, object>() { { "id", ids.Select(x => x.id).ToArray() } });
  331. // list = await azureCosmosFactory.DeleteTTL(list);
  332. // return ids;
  333. // }
  334. // else
  335. // {
  336. // int pages = (int)Math.Ceiling((double)ids.Count / pageSize);
  337. // Stopwatch stopwatch = Stopwatch.StartNew();
  338. // for (int i = 0; i < pages; i++)
  339. // {
  340. // List<IdPk> lists = ids.Skip((i) * pageSize).Take(pageSize).ToList();
  341. // List<Task> tasks = new List<Task>(lists.Count);
  342. // lists.ForEach(item =>
  343. // {
  344. // tasks.Add(container.container.DeleteItemStreamAsync(item.id, new PartitionKey(item.pk))
  345. // .ContinueWith((Task<Response> task) =>
  346. // {
  347. // using (Response response = task.Result)
  348. // {
  349. // idPks.Add(new IdPk { id = item.id, pk = item.pk, Status = response.Status });
  350. // // if (!response.IsSuccessStatusCode)
  351. // // {
  352. // // }
  353. // }
  354. // }
  355. // ));
  356. // });
  357. // await Task.WhenAll(tasks);
  358. // if (container.cache && RedisHelper.Instance != null)
  359. // {
  360. // lists.ForEach(async x => {
  361. // await RedisHelper.HDelAsync(CacheCosmosPrefix + container.container.Id, x.id);
  362. // });
  363. // }
  364. // }
  365. // stopwatch.Stop();
  366. // return idPks;
  367. // }
  368. // }
  369. // public static async Task<List<IdPk>> DeleteAll<T>(this AzureCosmosFactory azureCosmosFactory, Dictionary<string, object> dict) where T : CosmosEntity
  370. // {
  371. // if (dict.Keys.Count > 0)
  372. // {
  373. // List<T> list = await azureCosmosFactory.FindByDict<T>(dict);
  374. // return await azureCosmosFactory.DeleteAll(list);
  375. // }
  376. // else
  377. // {
  378. // throw new BizException("参数为空", 500);
  379. // }
  380. // }
  381. // public static async Task<List<IdPk>> DeleteAll<T>(this AzureCosmosFactory azureCosmosFactory, JsonElement dict) where T : CosmosEntity
  382. // {
  383. // List<T> list = await azureCosmosFactory.FindByDict<T>(dict);
  384. // return await azureCosmosFactory.DeleteAll(list);
  385. // }
  386. // public static async Task<List<IdPk>> DeleteAll<T>(this AzureCosmosFactory azureCosmosFactory, List<T> enyites) where T : CosmosEntity
  387. // {
  388. // Type type = typeof(T);
  389. // AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
  390. // List<IdPk> idPks = new List<IdPk>();
  391. // string pk = AzureCosmosUtil.GetPartitionKey(type);
  392. // if (container.monitor)
  393. // {
  394. // enyites = await azureCosmosFactory.DeleteTTL(enyites);
  395. // foreach (T t in enyites)
  396. // {
  397. // object o = type.GetProperty(pk).GetValue(t, null);
  398. // idPks.Add(new IdPk { id = t.id, pk = o.ToString(), StatusCode = HttpStatusCode.NoContent });
  399. // }
  400. // return idPks;
  401. // }
  402. // else
  403. // {
  404. // int pages = (int)Math.Ceiling((double)enyites.Count / pageSize);
  405. // Stopwatch stopwatch = Stopwatch.StartNew();
  406. // for (int i = 0; i < pages; i++)
  407. // {
  408. // List<T> lists = enyites.Skip((i) * pageSize).Take(pageSize).ToList();
  409. // List<KeyValuePair<PartitionKey, string>> itemsToInsert = new List<KeyValuePair<PartitionKey, string>>();
  410. // lists.ForEach(x =>
  411. // {
  412. // object o = type.GetProperty(pk).GetValue(x, null);
  413. // KeyValuePair<PartitionKey, string> keyValue = new KeyValuePair<PartitionKey, string>(new PartitionKey(o.ToString()), x.id);
  414. // itemsToInsert.Add(keyValue);
  415. // });
  416. // List<Task> tasks = new List<Task>(lists.Count);
  417. // itemsToInsert.ForEach(item =>
  418. // {
  419. // tasks.Add(container.container.DeleteItemStreamAsync(item.Value, item.Key)
  420. // .ContinueWith((Task<Response> task) =>
  421. // {
  422. // using (Response response = task.Result)
  423. // {
  424. // idPks.Add(new IdPk { id = item.Value, pk = item.Key.ToString(), Status = response.Status });
  425. // }
  426. // }
  427. // ));
  428. // });
  429. // await Task.WhenAll(tasks); if (container.cache && RedisHelper.Instance != null)
  430. // {
  431. // lists.ForEach(async x => {
  432. // await RedisHelper.HDelAsync(CacheCosmosPrefix + container.container.Id, x.id);
  433. // });
  434. // }
  435. // }
  436. // stopwatch.Stop();
  437. // return idPks;
  438. // }
  439. // }
  440. // public static async Task<IdPk> DeleteAsync<T>(this AzureCosmosFactory azureCosmosFactory, IdPk idPk) where T : CosmosEntity
  441. // {
  442. // return await DeleteAsync<T>(azureCosmosFactory, idPk.id, idPk.pk);
  443. // }
  444. // public static async Task<IdPk> DeleteAsync<T>(this AzureCosmosFactory azureCosmosFactory, string id, string pk) where T : CosmosEntity
  445. // {
  446. // // pk =AzureCosmosUtil.GetPartitionKey<T>();
  447. // AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
  448. // if (container.monitor)
  449. // {
  450. // List<T> list = await FindByDict<T>(azureCosmosFactory, new Dictionary<string, object>() { { "id", id } });
  451. // if (list.Count > 0)
  452. // {
  453. // await DeleteTTL<T>(azureCosmosFactory, list);
  454. // return new IdPk { id = id, pk = pk, StatusCode = HttpStatusCode.NoContent };
  455. // }
  456. // else
  457. // {
  458. // throw new BizException("未找到ID匹配的数据,删除失败");
  459. // }
  460. // }
  461. // else
  462. // {
  463. // Response response = await container.container.DeleteItemStreamAsync(id: id, partitionKey: new PartitionKey(pk));
  464. // if (container.cache && RedisHelper.Instance != null)
  465. // {
  466. // await RedisHelper.HDelAsync(CacheCosmosPrefix + container.container.Id, id);
  467. // }
  468. // return new IdPk { id = id, pk = pk, Status = response.Status };
  469. // }
  470. // }
  471. // public static async Task<IdPk> DeleteAsync<T>(this AzureCosmosFactory azureCosmosFactory, T entity) where T : CosmosEntity
  472. // {
  473. // Type type = typeof(T);
  474. // AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
  475. // string partitionKey = AzureCosmosUtil.GetPartitionKey(type);
  476. // object o = type.GetProperty(partitionKey).GetValue(entity, null);
  477. // if (container.monitor)
  478. // {
  479. // await DeleteTTL<T>(azureCosmosFactory, new List<T>() { entity });
  480. // return new IdPk { id = entity.id, pk = o.ToString(), StatusCode = HttpStatusCode.NoContent };
  481. // }
  482. // else
  483. // {
  484. // Response response = await container.container.DeleteItemStreamAsync(id: entity.id, partitionKey: new PartitionKey(o.ToString()));
  485. // if (container.cache && RedisHelper.Instance != null)
  486. // {
  487. // await RedisHelper.HDelAsync(CacheCosmosPrefix + container.container.Id, entity.id);
  488. // }
  489. // return new IdPk { id = entity.id, pk = partitionKey, Status = response.Status };
  490. // }
  491. // }
  492. // public static async Task<List<T>> FindSQL<T>(this AzureCosmosFactory azureCosmosFactory, string sql, Dictionary<string, object> Parameters = null) where T : CosmosEntity
  493. // {
  494. // if (sql.Contains(".pk"))
  495. // {
  496. // AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
  497. // QueryRequestOptions queryOptions = GetQueryRequestOptions(GetEffectivePageSize(-1, null));
  498. // if (Parameters != null)
  499. // {
  500. // AzureCosmosQuery cosmosDbQuery = new AzureCosmosQuery
  501. // {
  502. // QueryText = sql,
  503. // Parameters = Parameters
  504. // };
  505. // AsyncPageable<T> feedIterator = container.container
  506. // .GetItemQueryIterator<T>(cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryOptions);
  507. // return await ResultsFromFeedIterator(feedIterator);
  508. // }
  509. // else
  510. // {
  511. // QueryDefinition queryDefinition = new QueryDefinition(sql);
  512. // return await ResultsFromFeedIterator<T>(container.container.GetItemQueryIterator<T>(queryDefinition));
  513. // }
  514. // }
  515. // else
  516. // {
  517. // throw new BizException("查询参数必须设置 .pk ", ResponseCode.PARAMS_ERROR);
  518. // }
  519. // }
  520. // /// <summary>
  521. // /// 偌TTL刉壺
  522. // /// </summary>
  523. // /// <typeparam name="T"></typeparam>
  524. // /// <param name="list"></param>
  525. // /// <returns></returns>
  526. // private static async Task<List<T>> DeleteTTL<T>(this AzureCosmosFactory azureCosmosFactory, List<T> list) where T : CosmosEntity
  527. // {
  528. // AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
  529. // list.ForEach(x => { x.ttl = ttl; });
  530. // list = await DeleteTTlALL(azureCosmosFactory, list);
  531. // if (container.cache && RedisHelper.Instance != null)
  532. // {
  533. // list.ForEach(async x => {
  534. // await RedisHelper.HDelAsync(CacheCosmosPrefix + container.container.Id, x.id);
  535. // });
  536. // }
  537. // return list;
  538. // }
  539. // private static async Task<List<T>> DeleteTTlALL<T>(this AzureCosmosFactory azureCosmosFactory, List<T> enyites) where T : CosmosEntity
  540. // {
  541. // Type type = typeof(T);
  542. // int pages = (int)Math.Ceiling((double)enyites.Count / pageSize);
  543. // AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
  544. // bool flag = false;
  545. // if (RedisHelper.Exists(CacheCosmosPrefix + container.container.Id))
  546. // {
  547. // flag = true;
  548. // }
  549. // string partitionKey = AzureCosmosUtil.GetPartitionKey(type);
  550. // Stopwatch stopwatch = Stopwatch.StartNew();
  551. // for (int i = 0; i < pages; i++)
  552. // {
  553. // List<T> lists = enyites.Skip((i) * pageSize).Take(pageSize).ToList();
  554. // List<KeyValuePair<PartitionKey, Stream>> itemsToInsert = new List<KeyValuePair<PartitionKey, Stream>>();
  555. // lists.ForEach(async x =>
  556. // {
  557. // x.pk = type.Name;
  558. // //x.ttl = null;
  559. // MemoryStream stream = new MemoryStream();
  560. // await JsonSerializer.SerializeAsync(stream, x, new JsonSerializerOptions { IgnoreNullValues = true });
  561. // object o = type.GetProperty(partitionKey).GetValue(x, null);
  562. // KeyValuePair<PartitionKey, Stream> keyValue = new KeyValuePair<PartitionKey, Stream>(new PartitionKey(o.ToString()), stream);
  563. // itemsToInsert.Add(keyValue);
  564. // });
  565. // List<Task> tasks = new List<Task>(lists.Count);
  566. // itemsToInsert.ForEach(item =>
  567. // {
  568. // tasks.Add(container.container.UpsertItemStreamAsync(item.Value, item.Key)
  569. // .ContinueWith((Task<Response> task) =>
  570. // {
  571. // //using (ResponseMessage response = task.Result)
  572. // //{
  573. // // if (!response.IsSuccessStatusCode)
  574. // // {
  575. // // }
  576. // //}
  577. // }
  578. // ));
  579. // });
  580. // await Task.WhenAll(tasks);
  581. // if (container.cache && RedisHelper.Instance != null)
  582. // {
  583. // lists.ForEach(async x => {
  584. // await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, x.id, x);
  585. // });
  586. // }
  587. // }
  588. // if (container.cache && RedisHelper.Instance != null && !flag)
  589. // {
  590. // await RedisHelper.ExpireAsync(CacheCosmosPrefix + container.container.Id, timeoutSeconds);
  591. // }
  592. // stopwatch.Stop();
  593. // return enyites;
  594. // }
  595. // private static QueryRequestOptions GetDefaultQueryRequestOptions(int? itemsPerPage = null, int? maxBufferedItemCount = null, int? maxConcurrency = null)
  596. // {
  597. // QueryRequestOptions queryRequestOptions = new QueryRequestOptions
  598. // {
  599. // MaxItemCount = itemsPerPage == -1 ? 1000 : itemsPerPage,
  600. // MaxBufferedItemCount = maxBufferedItemCount ?? 100,
  601. // MaxConcurrency = maxConcurrency ?? 50
  602. // };
  603. // return queryRequestOptions;
  604. // }
  605. // private static int GetEffectivePageSize(int itemsPerPage, int? maxItemCount)
  606. // {
  607. // return itemsPerPage == -1 ? maxItemCount ?? itemsPerPage : Math.Min(maxItemCount ?? itemsPerPage, itemsPerPage);
  608. // }
  609. // private static async Task<List<T>> ResultsFromQueryAndOptions<T>(this AzureCosmosFactory azureCosmosFactory, AzureCosmosQuery cosmosDbQuery, QueryRequestOptions queryOptions)
  610. // {
  611. // if (cosmosDbQuery == null)
  612. // {
  613. // return null;
  614. // }
  615. // AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
  616. // AsyncPageable<T> query = container.container.GetItemQueryIterator<T>(
  617. // queryDefinition: cosmosDbQuery.CosmosQueryDefinition,
  618. // requestOptions: queryOptions);
  619. // return await ResultsFromFeedIterator(query);
  620. // }
  621. // private static async Task<List<T>> ResultsFromFeedIterator<T>(AsyncPageable<T> query, int? maxItemCount = null)
  622. // {
  623. // List<T> results = new List<T>();
  624. // await foreach (T t in query)
  625. // {
  626. // results.Add(t);
  627. // if (results.Count == maxItemCount)
  628. // {
  629. // return results;
  630. // }
  631. // }
  632. // return results;
  633. // }
  634. // private static QueryRequestOptions GetQueryRequestOptions(int itemsPerPage)
  635. // {
  636. // QueryRequestOptions queryRequestOptions = new QueryRequestOptions
  637. // {
  638. // MaxItemCount = itemsPerPage
  639. // };
  640. // return queryRequestOptions;
  641. // }
  642. // }
  643. // #endregion
  644. //}
  645. //}