SelectTable.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. // 麻省理工学院许可证
  2. //
  3. // 版权所有 (c) 2021-2023 zuohuaijun,大名科技(天津)有限公司 联系电话/微信:18020030720 QQ:515096995
  4. //
  5. // 特此免费授予获得本软件的任何人以处理本软件的权利,但须遵守以下条件:在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
  6. //
  7. // 软件按“原样”提供,不提供任何形式的明示或暗示的保证,包括但不限于对适销性、适用性和非侵权的保证。
  8. // 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是因合同、侵权或其他方式引起的,与软件或其使用或其他交易有关。
  9. namespace Admin.NET.Core.Service;
  10. using AspectCore.Extensions.Reflection;
  11. using NewLife.Data;
  12. using Newtonsoft.Json.Linq;
  13. using Newtonsoft.Json.Schema;
  14. using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
  15. using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
  16. using SqlSugar;
  17. using StackExchange.Redis;
  18. using System;
  19. using System.Collections;
  20. using System.Collections.Generic;
  21. using System.Dynamic;
  22. using System.Linq;
  23. using System.Text.RegularExpressions;
  24. /// <summary>
  25. ///
  26. /// </summary>
  27. public class SelectTable : ISingleton
  28. {
  29. private readonly IdentityService _identitySvc;
  30. private readonly TableMapper _tableMapper;
  31. private readonly ISqlSugarClient _db;
  32. /// <summary>
  33. ///
  34. /// </summary>
  35. /// <param name="identityService"></param>
  36. /// <param name="tableMapper"></param>
  37. /// <param name="dbClient"></param>
  38. public SelectTable(IdentityService identityService, TableMapper tableMapper, ISqlSugarClient dbClient)
  39. {
  40. _identitySvc = identityService;
  41. _tableMapper = tableMapper;
  42. _db = dbClient;
  43. }
  44. /// <summary>
  45. /// 判断表名是否正确,如果不正确则抛异常
  46. /// </summary>
  47. /// <param name="table"></param>
  48. /// <returns></returns>
  49. public virtual bool IsTable(string table)
  50. {
  51. if (_db.DbMaintenance.GetTableInfoList().Any(it => it.Name.Equals(table, StringComparison.CurrentCultureIgnoreCase)))
  52. return true;
  53. else
  54. throw new Exception($"表名【{table}】不正确!");
  55. }
  56. /// <summary>
  57. /// 判断表的列名是否正确,如果不正确则抛异常,更早地暴露给调用方
  58. /// </summary>
  59. /// <param name="table"></param>
  60. /// <param name="col"></param>
  61. /// <returns></returns>
  62. public virtual bool IsCol(string table, string col)
  63. {
  64. if (_db.DbMaintenance.GetColumnInfosByTableName(table).Any(it => it.DbColumnName.Equals(col, StringComparison.CurrentCultureIgnoreCase)))
  65. return true;
  66. else
  67. throw new Exception($"表【{table}】不存在列【{col}】!请检查输入参数");
  68. }
  69. /// <summary>
  70. ///
  71. /// </summary>
  72. /// <param name="subtable"></param>
  73. /// <param name="page"></param>
  74. /// <param name="count"></param>
  75. /// <param name="json"></param>
  76. /// <param name="dd"></param>
  77. /// <returns></returns>
  78. public virtual Tuple<dynamic, int> GetTableData(string subtable, int page, int count, int query, string json, JObject dd)
  79. {
  80. var role = _identitySvc.GetSelectRole(subtable);
  81. if (!role.Item1)//没有权限返回异常
  82. {
  83. throw new Exception(role.Item2);
  84. }
  85. string selectrole = role.Item2;
  86. subtable = _tableMapper.GetTableName(subtable);
  87. JObject values = JObject.Parse(json);
  88. page = values["page"] == null ? page : int.Parse(values["page"].ToString());
  89. count = values["count"] == null ? count : int.Parse(values["count"].ToString());
  90. query = values["query"] == null ? query : int.Parse(values["query"].ToString());
  91. values.Remove("page");
  92. values.Remove("count");
  93. var tb = sugarQueryable(subtable, selectrole, values, dd);
  94. if (query == 1)//1-总数
  95. return new Tuple<dynamic, int>(new List<object>(), tb.Count());
  96. else
  97. {
  98. if (count > 0)
  99. {
  100. int total = 0;
  101. if (query == 0)//0-对象
  102. return new Tuple<dynamic, int>(tb.ToPageList(page, count), total);
  103. else
  104. //2-以上全部
  105. return new Tuple<dynamic, int>(tb.ToPageList(page, count, ref total), total);
  106. }
  107. else
  108. {
  109. if (query == 0)
  110. return new Tuple<dynamic, int>(tb.ToList(), 0);
  111. else
  112. return new Tuple<dynamic, int>(tb.ToList(), tb.Count());
  113. }
  114. }
  115. }
  116. /// <summary>
  117. /// 解析并查询
  118. /// </summary>
  119. /// <param name="query"></param>
  120. /// <returns></returns>
  121. public virtual JObject Query(string queryJson)
  122. {
  123. JObject resultObj = new JObject();
  124. JObject queryJobj = JObject.Parse(queryJson);
  125. resultObj = Query(queryJobj);
  126. return resultObj;
  127. }
  128. /// <summary>
  129. /// 单表查询
  130. /// </summary>
  131. /// <param name="queryObj"></param>
  132. /// <param name="nodeName">返回数据的节点名称 默认为 infos</param>
  133. /// <returns></returns>
  134. public virtual JObject QuerySingle(JObject queryObj, string nodeName = "infos")
  135. {
  136. JObject resultObj = new JObject();
  137. int total = 0;
  138. foreach (var item in queryObj)
  139. {
  140. string key = item.Key.Trim();
  141. if (key.EndsWith("[]"))
  142. {
  143. total = QuerySingleList(resultObj, item, nodeName);
  144. }
  145. else if (key.Equals("func"))
  146. {
  147. ExecFunc(resultObj, item);
  148. }
  149. else if (key.Equals("total@") || key.Equals("total"))
  150. {
  151. resultObj.Add("total", total);
  152. }
  153. }
  154. return resultObj;
  155. }
  156. /// <summary>
  157. /// 获取查询语句
  158. /// </summary>
  159. /// <param name="queryObj"></param>
  160. /// <returns></returns>
  161. public virtual string ToSql(JObject queryObj)
  162. {
  163. foreach (var item in queryObj)
  164. {
  165. string key = item.Key.Trim();
  166. if (key.EndsWith("[]"))
  167. {
  168. return ToSql(item);
  169. }
  170. }
  171. return string.Empty;
  172. }
  173. /// <summary>
  174. /// 解析并查询
  175. /// </summary>
  176. /// <param name="query"></param>
  177. /// <returns></returns>
  178. public virtual JObject Query(JObject queryObj)
  179. {
  180. JObject resultObj = new JObject();
  181. int total = 0;
  182. foreach (var item in queryObj)
  183. {
  184. string key = item.Key.Trim();
  185. if (key.Equals("[]"))
  186. {
  187. total = QueryMoreList(resultObj, item);
  188. }
  189. else if (key.EndsWith("[]"))
  190. {
  191. total = QuerySingleList(resultObj, item);
  192. }
  193. else if (key.Equals("func"))
  194. {
  195. ExecFunc(resultObj, item);
  196. }
  197. else if (key.Equals("total@") || key.Equals("total"))
  198. {
  199. resultObj.Add("total", total);
  200. }
  201. else
  202. {
  203. var template = GetFirstData(key, item.Value.ToString(), resultObj);
  204. if (template != null)
  205. {
  206. resultObj.Add(key, JToken.FromObject(template));
  207. }
  208. }
  209. }
  210. return resultObj;
  211. }
  212. //动态调用方法
  213. private object ExecFunc(string funcname, object[] param, Type[] types)
  214. {
  215. var method = typeof(FuncList).GetMethod(funcname);
  216. var reflector = method.GetReflector();
  217. var result = reflector.Invoke(new FuncList(), param);
  218. return result;
  219. }
  220. //生成sql
  221. private string ToSql(string subtable, int page, int count, int query, string json)
  222. {
  223. JObject values = JObject.Parse(json);
  224. page = values["page"] == null ? page : int.Parse(values["page"].ToString());
  225. count = values["count"] == null ? count : int.Parse(values["count"].ToString());
  226. query = values["query"] == null ? query : int.Parse(values["query"].ToString());
  227. values.Remove("page");
  228. values.Remove("count");
  229. subtable = _tableMapper.GetTableName(subtable);
  230. var tb = sugarQueryable(subtable, "*", values, null);
  231. var sqlObj = tb.Skip((page - 1) * count).Take(10).ToSql();
  232. return sqlObj.Key;
  233. }
  234. //
  235. private dynamic GetFirstData(string subtable, string json, JObject job)
  236. {
  237. var role = _identitySvc.GetSelectRole(subtable);
  238. if (!role.Item1)//没有权限返回异常
  239. {
  240. throw new Exception(role.Item2);
  241. }
  242. string selectrole = role.Item2;
  243. subtable = _tableMapper.GetTableName(subtable);
  244. JObject values = JObject.Parse(json);
  245. values.Remove("page");
  246. values.Remove("count");
  247. //todo *
  248. var tb = sugarQueryable(subtable, selectrole, values, job).First();
  249. var dic = (IDictionary<string, object>)tb;
  250. foreach (var item in values.Properties().Where(it => it.Name.EndsWith("()")))
  251. {
  252. if (item.Value.HasValue())
  253. {
  254. string func = item.Value.ToString().Substring(0, item.Value.ToString().IndexOf("("));
  255. string param = item.Value.ToString().Substring(item.Value.ToString().IndexOf("(") + 1).TrimEnd(')');
  256. var types = new List<Type>();
  257. var paramss = new List<object>();
  258. foreach (var va in param.Split(','))
  259. {
  260. types.Add(typeof(object));
  261. paramss.Add(tb.Where(it => it.Key.Equals(va)).Select(i => i.Value));
  262. }
  263. dic[item.Name] = ExecFunc(func, paramss.ToArray(), types.ToArray());
  264. }
  265. }
  266. return tb;
  267. }
  268. //单表查询,返回的数据在指定的NodeName节点
  269. private int QuerySingleList(JObject resultObj, KeyValuePair<string, JToken> item, string nodeName)
  270. {
  271. string key = item.Key.Trim();
  272. var jb = JObject.Parse(item.Value.ToString());
  273. int page = jb["page"] == null ? 0 : int.Parse(jb["page"].ToString());
  274. int count = jb["count"] == null ? 10 : int.Parse(jb["count"].ToString());
  275. int query = jb["query"] == null ? 0 : int.Parse(jb["query"].ToString());
  276. int total = 0;
  277. jb.Remove("page"); jb.Remove("count"); jb.Remove("query");
  278. var htt = new JArray();
  279. foreach (var t in jb)
  280. {
  281. var datas = GetTableData(t.Key, page, count, query, t.Value.ToString(), null);
  282. if (query > 0)
  283. {
  284. total = datas.Item2;
  285. }
  286. foreach (var data in datas.Item1)
  287. {
  288. htt.Add(JToken.FromObject(data));
  289. }
  290. }
  291. if (!string.IsNullOrEmpty(nodeName))
  292. {
  293. resultObj.Add(nodeName, htt);
  294. }
  295. else
  296. resultObj.Add(key, htt);
  297. return total;
  298. }
  299. //生成sql
  300. private string ToSql(KeyValuePair<string, JToken> item)
  301. {
  302. string key = item.Key.Trim();
  303. var jb = JObject.Parse(item.Value.ToString());
  304. int page = jb["page"] == null ? 0 : int.Parse(jb["page"].ToString());
  305. int count = jb["count"] == null ? 10 : int.Parse(jb["count"].ToString());
  306. int query = jb["query"] == null ? 0 : int.Parse(jb["query"].ToString());
  307. jb.Remove("page"); jb.Remove("count"); jb.Remove("query");
  308. var htt = new JArray();
  309. foreach (var t in jb)
  310. {
  311. return ToSql(t.Key, page, count, query, t.Value.ToString());
  312. }
  313. return string.Empty;
  314. }
  315. //单表查询
  316. private int QuerySingleList(JObject resultObj, KeyValuePair<string, JToken> item)
  317. {
  318. string key = item.Key.Trim();
  319. return QuerySingleList(resultObj, item, key);
  320. }
  321. //多列表查询
  322. private int QueryMoreList(JObject resultObj, KeyValuePair<string, JToken> item)
  323. {
  324. int total = 0;
  325. var jb = JObject.Parse(item.Value.ToString());
  326. var page = jb["page"] == null ? 0 : int.Parse(jb["page"].ToString());
  327. var count = jb["count"] == null ? 10 : int.Parse(jb["count"].ToString());
  328. var query = jb["query"] == null ? 0 : int.Parse(jb["query"].ToString());
  329. jb.Remove("page"); jb.Remove("count"); jb.Remove("query");
  330. var htt = new JArray();
  331. List<string> tables = new List<string>(), where = new List<string>();
  332. foreach (var t in jb)
  333. {
  334. tables.Add(t.Key); where.Add(t.Value.ToString());
  335. }
  336. if (tables.Count > 0)
  337. {
  338. string table = tables[0];
  339. var temp = GetTableData(table, page, count, query, where[0], null);
  340. if (query > 0)
  341. {
  342. total = temp.Item2;
  343. }
  344. foreach (var dd in temp.Item1)
  345. {
  346. var zht = new JObject();
  347. zht.Add(table, JToken.FromObject(dd));
  348. for (int i = 1; i < tables.Count; i++)
  349. {
  350. string subtable = tables[i];
  351. if (subtable.EndsWith("[]"))
  352. {
  353. subtable = subtable.TrimEnd("[]".ToCharArray());
  354. var jbb = JObject.Parse(where[i]);
  355. page = jbb["page"] == null ? 0 : int.Parse(jbb["page"].ToString());
  356. count = jbb["count"] == null ? 0 : int.Parse(jbb["count"].ToString());
  357. var lt = new JArray();
  358. foreach (var d in GetTableData(subtable, page, count, query, jbb[subtable].ToString(), zht).Item1)
  359. {
  360. lt.Add(JToken.FromObject(d));
  361. }
  362. zht.Add(tables[i], lt);
  363. }
  364. else
  365. {
  366. var ddf = GetFirstData(subtable, where[i].ToString(), zht);
  367. if (ddf != null)
  368. {
  369. zht.Add(subtable, JToken.FromObject(ddf));
  370. }
  371. }
  372. }
  373. htt.Add(zht);
  374. }
  375. }
  376. if (query != 1)
  377. {
  378. resultObj.Add("[]", htt);
  379. }
  380. return total;
  381. }
  382. //执行方法
  383. private void ExecFunc(JObject resultObj, KeyValuePair<string, JToken> item)
  384. {
  385. JObject jb = JObject.Parse(item.Value.ToString());
  386. Type type = typeof(FuncList);
  387. var dataJObj = new JObject();
  388. foreach (var f in jb)
  389. {
  390. var types = new List<Type>();
  391. var param = new List<object>();
  392. foreach (var va in JArray.Parse(f.Value.ToString()))
  393. {
  394. types.Add(typeof(object));
  395. param.Add(va);
  396. }
  397. dataJObj.Add(f.Key, JToken.FromObject(ExecFunc(f.Key, param.ToArray(), types.ToArray())));
  398. }
  399. resultObj.Add("func", dataJObj);
  400. }
  401. //
  402. private ISugarQueryable<ExpandoObject> sugarQueryable(string subtable, string selectrole, JObject values, JObject dd)
  403. {
  404. IsTable(subtable);
  405. var tb = _db.Queryable(subtable, "tb");
  406. if (values["@column"].HasValue())
  407. {
  408. ProcessColumn(subtable, selectrole, values, tb);
  409. }
  410. else
  411. {
  412. tb.Select(selectrole);
  413. }
  414. List<IConditionalModel> conModels = new List<IConditionalModel>();
  415. if (values["identity"].HasValue())
  416. {
  417. conModels.Add(new ConditionalModel() { FieldName = values["identity"].ToString(), ConditionalType = ConditionalType.Equal, FieldValue = _identitySvc.GetUserIdentity() });
  418. }
  419. foreach (var va in values)
  420. {
  421. string vakey = va.Key.Trim();
  422. string fieldValue = va.Value.ToString();
  423. if (vakey.StartsWith("@"))
  424. {
  425. continue;
  426. }
  427. if (vakey.EndsWith("$"))//模糊查询
  428. {
  429. FuzzyQuery(subtable, conModels, va);
  430. }
  431. else if (vakey.EndsWith("{}"))//逻辑运算
  432. {
  433. ConditionQuery(subtable, conModels, va);
  434. }
  435. else if (vakey.EndsWith("%"))//bwtween查询
  436. {
  437. ConditionBetween(subtable, conModels, va);
  438. }
  439. else if (vakey.EndsWith("@") && dd != null) // 关联上一个table
  440. {
  441. string[] str = fieldValue.Split('/');
  442. string value = string.Empty;
  443. if (str.Length == 3)
  444. {
  445. value = dd[str[1]][str[2]].ToString();
  446. }
  447. else if (str.Length == 2)
  448. {
  449. value = dd[str[0]][str[1]].ToString();
  450. }
  451. conModels.Add(new ConditionalModel() { FieldName = vakey.TrimEnd('@'), ConditionalType = ConditionalType.Equal, FieldValue = value });
  452. }
  453. else if (vakey.EndsWith("~"))//不等于
  454. {
  455. conModels.Add(new ConditionalModel() { FieldName = vakey.TrimEnd('~'), ConditionalType = ConditionalType.NoEqual, FieldValue = fieldValue });
  456. }
  457. else if (IsCol(subtable, vakey)) //其他where条件
  458. {
  459. if (string.IsNullOrEmpty(fieldValue))
  460. {
  461. conModels.Add(new ConditionalModel() { FieldName = vakey, ConditionalType = ConditionalType.IsNullOrEmpty });//增加null、""匹配
  462. }
  463. else
  464. {
  465. conModels.Add(new ConditionalModel() { FieldName = vakey, ConditionalType = ConditionalType.Equal, FieldValue = fieldValue });
  466. }
  467. }
  468. }
  469. tb.Where(conModels);
  470. //排序
  471. ProcessOrder(subtable, values, tb);
  472. //分组
  473. PrccessGroup(subtable, values, tb);
  474. //Having
  475. ProcessHaving(values, tb);
  476. return tb;
  477. }
  478. //处理字段重命名 "@column":"toId:parentId",对应SQL是toId AS parentId,将查询的字段toId变为parentId返回
  479. private void ProcessColumn(string subtable, string selectrole, JObject values, ISugarQueryable<ExpandoObject> tb)
  480. {
  481. var str = new System.Text.StringBuilder(100);
  482. foreach (var item in values["@column"].ToString().Split(','))
  483. {
  484. string[] ziduan = item.Split(':');
  485. string colName = ziduan[0];
  486. var ma = new Regex(@"\((\w+)\)").Match(colName);
  487. //处理max,min这样的函数
  488. if (ma.Success && ma.Groups.Count > 1)
  489. {
  490. colName = ma.Groups[1].Value;
  491. }
  492. //判断列表是否有权限 sum(1),sum(*),Count(1)这样的值直接有效
  493. if (colName == "*" || int.TryParse(colName, out int colNumber) || (IsCol(subtable, colName) && _identitySvc.ColIsRole(colName, selectrole.Split(','))))
  494. {
  495. if (ziduan.Length > 1)
  496. {
  497. if (ziduan[1].Length > 20)
  498. {
  499. throw new Exception("别名不能超过20个字符");
  500. }
  501. str.Append(ziduan[0] + " as `" + ReplaceSQLChar(ziduan[1]) + "`,");
  502. }
  503. //不对函数加``,解决sum(*),Count(1)等不能使用的问题
  504. else if (ziduan[0].Contains('('))
  505. {
  506. str.Append(ziduan[0] + ",");
  507. }
  508. else
  509. str.Append("`" + ziduan[0] + "`" + ",");
  510. }
  511. }
  512. if (string.IsNullOrEmpty(str.ToString()))
  513. {
  514. throw new Exception($"表名{subtable}没有可查询的字段!");
  515. }
  516. tb.Select(str.ToString().TrimEnd(','));
  517. }
  518. // "@having":"function0(...)?value0;function1(...)?value1;function2(...)?value2...",
  519. // SQL函数条件,一般和 @group一起用,函数一般在 @column里声明
  520. private void ProcessHaving(JObject values, ISugarQueryable<ExpandoObject> tb)
  521. {
  522. if (values["@having"].HasValue())
  523. {
  524. List<IConditionalModel> hw = new List<IConditionalModel>();
  525. List<string> havingItems = new List<string>();
  526. if (values["@having"].HasValues)
  527. {
  528. havingItems = values["@having"].Select(p => p.ToString()).ToList();
  529. }
  530. else
  531. {
  532. havingItems.Add(values["@having"].ToString());
  533. }
  534. foreach (var item in havingItems)
  535. {
  536. string and = item.ToString();
  537. var model = new ConditionalModel();
  538. if (and.Contains(">="))
  539. {
  540. model.FieldName = and.Split(new string[] { ">=" }, StringSplitOptions.RemoveEmptyEntries)[0];
  541. model.ConditionalType = ConditionalType.GreaterThanOrEqual;
  542. model.FieldValue = and.Split(new string[] { ">=" }, StringSplitOptions.RemoveEmptyEntries)[1];
  543. }
  544. else if (and.Contains("<="))
  545. {
  546. model.FieldName = and.Split(new string[] { "<=" }, StringSplitOptions.RemoveEmptyEntries)[0];
  547. model.ConditionalType = ConditionalType.LessThanOrEqual;
  548. model.FieldValue = and.Split(new string[] { "<=" }, StringSplitOptions.RemoveEmptyEntries)[1];
  549. }
  550. else if (and.Contains(">"))
  551. {
  552. model.FieldName = and.Split(new string[] { ">" }, StringSplitOptions.RemoveEmptyEntries)[0];
  553. model.ConditionalType = ConditionalType.GreaterThan;
  554. model.FieldValue = and.Split(new string[] { ">" }, StringSplitOptions.RemoveEmptyEntries)[1];
  555. }
  556. else if (and.Contains("<"))
  557. {
  558. model.FieldName = and.Split(new string[] { "<" }, StringSplitOptions.RemoveEmptyEntries)[0];
  559. model.ConditionalType = ConditionalType.LessThan;
  560. model.FieldValue = and.Split(new string[] { "<" }, StringSplitOptions.RemoveEmptyEntries)[1];
  561. }
  562. else if (and.Contains("!="))
  563. {
  564. model.FieldName = and.Split(new string[] { "!=" }, StringSplitOptions.RemoveEmptyEntries)[0];
  565. model.ConditionalType = ConditionalType.NoEqual;
  566. model.FieldValue = and.Split(new string[] { "!=" }, StringSplitOptions.RemoveEmptyEntries)[1];
  567. }
  568. else if (and.Contains("="))
  569. {
  570. model.FieldName = and.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries)[0];
  571. model.ConditionalType = ConditionalType.Equal;
  572. model.FieldValue = and.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries)[1];
  573. }
  574. hw.Add(model);
  575. }
  576. //var d = db.Context.Utilities.ConditionalModelToSql(hw);
  577. //tb.Having(d.Key, d.Value);
  578. tb.Having(string.Join(",", havingItems));
  579. }
  580. }
  581. //"@group":"column0,column1...",分组方式。如果 @column里声明了Table的id,则id也必须在 @group中声明;其它情况下必须满足至少一个条件:
  582. //1.分组的key在 @column里声明
  583. //2.Table主键在 @group中声明
  584. private void PrccessGroup(string subtable, JObject values, ISugarQueryable<ExpandoObject> tb)
  585. {
  586. if (values["@group"].HasValue())
  587. {
  588. List<GroupByModel> groupList = new();//多库兼容写法
  589. foreach (var col in values["@group"].ToString().Split(','))
  590. {
  591. if (IsCol(subtable, col))
  592. {
  593. //str.Append(and + ",");
  594. groupList.Add(new GroupByModel() { FieldName = col });
  595. }
  596. }
  597. if (groupList.Any())
  598. {
  599. tb.GroupBy(groupList);
  600. }
  601. }
  602. }
  603. //处理排序 "@order":"name-,id"查询按 name降序、id默认顺序 排序的User数组
  604. private void ProcessOrder(string subtable, JObject values, ISugarQueryable<ExpandoObject> tb)
  605. {
  606. if (values["@order"].HasValue())
  607. {
  608. List<OrderByModel> orderList = new(); //多库兼容写法
  609. foreach (var item in values["@order"].ToString().Split(','))
  610. {
  611. string col = item.Replace("-", "").Replace("+", "").Replace(" desc", "").Replace(" asc", "");//增加对原生排序的支持
  612. if (IsCol(subtable, col))
  613. {
  614. orderList.Add(new OrderByModel()
  615. {
  616. FieldName = col,
  617. OrderByType = item.EndsWith("-") || item.EndsWith(" desc") ? OrderByType.Desc : OrderByType.Asc
  618. });
  619. }
  620. }
  621. if (orderList.Any())
  622. {
  623. tb.OrderBy(orderList);
  624. }
  625. }
  626. }
  627. //条件查询 "key{}":"条件0,条件1...",条件为任意SQL比较表达式字符串,非Number类型必须用''包含条件的值,如'a'
  628. //&, |, ! 逻辑运算符,对应数据库 SQL 中的 AND, OR, NOT。
  629. // 横或纵与:同一字段的值内条件默认 | 或连接,不同字段的条件默认 & 与连接。
  630. // ① & 可用于"key&{}":"条件"等
  631. // ② | 可用于"key|{}":"条件", "key|{}":[] 等,一般可省略
  632. // ③ ! 可单独使用,如"key!":Object,也可像&,|一样配合其他功能符使用
  633. private void ConditionQuery(string subtable, List<IConditionalModel> conModels, KeyValuePair<string, JToken> va)
  634. {
  635. string vakey = va.Key.Trim();
  636. string field = vakey.TrimEnd("{}".ToCharArray());
  637. if (va.Value.HasValues)
  638. {
  639. List<string> inValues = new List<string>();
  640. foreach (var cm in va.Value)
  641. {
  642. inValues.Add(cm.ToString());
  643. }
  644. conModels.Add(new ConditionalModel()
  645. {
  646. FieldName = field.TrimEnd("!".ToCharArray()),
  647. ConditionalType = field.EndsWith("!") ? ConditionalType.NotIn : ConditionalType.In,
  648. FieldValue = string.Join(",", inValues)
  649. });
  650. }
  651. else
  652. {
  653. var ddt = new List<KeyValuePair<WhereType, ConditionalModel>>();
  654. foreach (var and in va.Value.ToString().Split(','))
  655. {
  656. var model = new ConditionalModel();
  657. model.FieldName = field.TrimEnd("&".ToCharArray());//处理&()的查询方式
  658. if (and.StartsWith(">="))
  659. {
  660. model.ConditionalType = ConditionalType.GreaterThanOrEqual;
  661. model.FieldValue = and.TrimStart(">=".ToCharArray());
  662. }
  663. else if (and.StartsWith("<="))
  664. {
  665. model.ConditionalType = ConditionalType.LessThanOrEqual;
  666. model.FieldValue = and.TrimStart("<=".ToCharArray());
  667. }
  668. else if (and.StartsWith(">"))
  669. {
  670. model.ConditionalType = ConditionalType.GreaterThan;
  671. model.FieldValue = and.TrimStart('>');
  672. }
  673. else if (and.StartsWith("<"))
  674. {
  675. model.ConditionalType = ConditionalType.LessThan;
  676. model.FieldValue = and.TrimStart('<');
  677. }
  678. ddt.Add(new KeyValuePair<WhereType, ConditionalModel>((field.EndsWith("&") ? WhereType.And : WhereType.Or), model));
  679. }
  680. conModels.Add(new ConditionalCollections() { ConditionalList = ddt });
  681. }
  682. }
  683. //"key%":"start,end" => "key%":["start,end"],其中 start 和 end 都只能为 Boolean, Number, String 中的一种,如 "2017-01-01,2019-01-01" ,["1,90000", "82001,100000"] ,可用于连续范围内的筛选
  684. private void ConditionBetween(string subtable, List<IConditionalModel> conModels, KeyValuePair<string, JToken> va)
  685. {
  686. string vakey = va.Key.Trim();
  687. string field = vakey.TrimEnd("%".ToCharArray());
  688. List<string> inValues = new List<string>();
  689. if (va.Value.HasValues)
  690. {
  691. foreach (var cm in va.Value)
  692. {
  693. inValues.Add(cm.ToString());
  694. }
  695. }
  696. else
  697. {
  698. inValues.Add(va.Value.ToString());
  699. }
  700. for (var i = 0; i < inValues.Count; i++)
  701. {
  702. var fileds = inValues[i].Split(',');
  703. if (fileds.Length == 2)
  704. {
  705. var ddt = new List<KeyValuePair<WhereType, ConditionalModel>>();
  706. var leftCondition = new ConditionalModel()
  707. {
  708. FieldName = field,
  709. ConditionalType = ConditionalType.GreaterThanOrEqual,
  710. FieldValue = fileds[0]
  711. };
  712. ddt.Add(new KeyValuePair<WhereType, ConditionalModel>(i == 0 ? WhereType.And : WhereType.Or, leftCondition));
  713. var rightCondition = new ConditionalModel()
  714. {
  715. FieldName = field,
  716. ConditionalType = ConditionalType.LessThanOrEqual,
  717. FieldValue = fileds[1]
  718. };
  719. ddt.Add(new KeyValuePair<WhereType, ConditionalModel>(WhereType.And, rightCondition));
  720. conModels.Add(new ConditionalCollections() { ConditionalList = ddt });
  721. }
  722. }
  723. }
  724. //模糊搜索 "key$":"SQL搜索表达式" => "key$":["SQL搜索表达式"],任意SQL搜索表达式字符串,如 %key%(包含key), key%(以key开始), %k%e%y%(包含字母k,e,y) 等,%表示任意字符
  725. private void FuzzyQuery(string subtable, List<IConditionalModel> conModels, KeyValuePair<string, JToken> va)
  726. {
  727. string vakey = va.Key.Trim();
  728. string fieldValue = va.Value.ToString();
  729. var conditionalType = ConditionalType.Like;
  730. if (IsCol(subtable, vakey.TrimEnd('$')))
  731. {
  732. //支持三种like查询
  733. if (fieldValue.StartsWith("%") && fieldValue.EndsWith("%"))
  734. {
  735. conditionalType = ConditionalType.Like;
  736. }
  737. else if (fieldValue.StartsWith("%"))
  738. {
  739. conditionalType = ConditionalType.LikeRight;
  740. }
  741. else if (fieldValue.EndsWith("%"))
  742. {
  743. conditionalType = ConditionalType.LikeLeft;
  744. }
  745. conModels.Add(new ConditionalModel() { FieldName = vakey.TrimEnd('$'), ConditionalType = conditionalType, FieldValue = fieldValue.TrimEnd("%".ToArray()).TrimStart("%".ToArray()) });
  746. }
  747. }
  748. //处理sql注入
  749. private string ReplaceSQLChar(string str)
  750. {
  751. if (str == String.Empty)
  752. return String.Empty;
  753. str = str.Replace("'", "");
  754. str = str.Replace(";", "");
  755. str = str.Replace(",", "");
  756. str = str.Replace("?", "");
  757. str = str.Replace("<", "");
  758. str = str.Replace(">", "");
  759. str = str.Replace("(", "");
  760. str = str.Replace(")", "");
  761. str = str.Replace("@", "");
  762. str = str.Replace("=", "");
  763. str = str.Replace("+", "");
  764. str = str.Replace("*", "");
  765. str = str.Replace("&", "");
  766. str = str.Replace("#", "");
  767. str = str.Replace("%", "");
  768. str = str.Replace("$", "");
  769. str = str.Replace("\"", "");
  770. //删除与数据库相关的词
  771. str = Regex.Replace(str, "delete from", "", RegexOptions.IgnoreCase);
  772. str = Regex.Replace(str, "drop table", "", RegexOptions.IgnoreCase);
  773. str = Regex.Replace(str, "truncate", "", RegexOptions.IgnoreCase);
  774. str = Regex.Replace(str, "xp_cmdshell", "", RegexOptions.IgnoreCase);
  775. str = Regex.Replace(str, "exec master", "", RegexOptions.IgnoreCase);
  776. str = Regex.Replace(str, "net localgroup administrators", "", RegexOptions.IgnoreCase);
  777. str = Regex.Replace(str, "net user", "", RegexOptions.IgnoreCase);
  778. str = Regex.Replace(str, "-", "", RegexOptions.IgnoreCase);
  779. str = Regex.Replace(str, "truncate", "", RegexOptions.IgnoreCase);
  780. return str;
  781. }
  782. /// <summary>
  783. /// 单条插入
  784. /// </summary>
  785. /// <param name="tableName"></param>
  786. /// <param name="cols"></param>
  787. /// <param name="role"></param>
  788. /// <returns>(各种类型的)id</returns>
  789. public object InsertSingle(string tableName, JObject cols, APIJSON_Role role = null)
  790. {
  791. role ??= _identitySvc.GetRole();
  792. var dt = new Dictionary<string, object>();
  793. foreach (var f in cols)//遍历字段
  794. {
  795. if (//f.Key.ToLower() != "id" && //是否一定要传id
  796. IsCol(tableName, f.Key) &&
  797. (role.Insert.Column.Contains("*") || role.Insert.Column.Contains(f.Key, StringComparer.CurrentCultureIgnoreCase)))
  798. dt.Add(f.Key, FuncList.TransJObjectToSugarPara(f.Value));
  799. }
  800. //如果外部没传id,就后端生成或使用数据库默认值,如果都没有会出错
  801. object id;
  802. if (!dt.ContainsKey("id"))
  803. {
  804. id = YitIdHelper.NextId();//自己生成id的方法,可以由外部传入
  805. dt.Add("id", id);
  806. }
  807. else
  808. {
  809. id = dt["id"];
  810. }
  811. _db.Insertable(dt).AS(tableName).ExecuteCommand();//根据主键类型设置返回雪花或自增,目前返回条数
  812. return id;
  813. }
  814. /// <summary>
  815. /// 为每天记录创建udpate sql
  816. /// </summary>
  817. /// <param name="tableName"></param>
  818. /// <param name="record"></param>
  819. /// <param name="role"></param>
  820. /// <returns></returns>
  821. public int UpdateSingleRecord(string tableName, JObject record, APIJSON_Role role = null)
  822. {
  823. role ??= _identitySvc.GetRole();
  824. if (!record.ContainsKey("id"))
  825. {
  826. throw Oops.Bah("未传主键id");
  827. }
  828. var dt = new Dictionary<string, object>();
  829. var sb = new StringBuilder(100);
  830. object id = null;
  831. foreach (var f in record)//遍历每个字段
  832. {
  833. if (f.Key.Equals("id", StringComparison.OrdinalIgnoreCase))
  834. {
  835. if (f.Value is JArray)//id数组
  836. {
  837. sb.Append($"{f.Key} in (@{f.Key})");
  838. id = FuncList.TransJArrayToSugarPara(f.Value);
  839. }
  840. else//单个id
  841. {
  842. sb.Append($"{f.Key}=@{f.Key}");
  843. id = FuncList.TransJObjectToSugarPara(f.Value);
  844. }
  845. }
  846. else if (IsCol(tableName, f.Key) && (role.Update.Column.Contains("*") || role.Update.Column.Contains(f.Key, StringComparer.CurrentCultureIgnoreCase)))
  847. {
  848. dt.Add(f.Key, FuncList.TransJObjectToSugarPara(f.Value));
  849. }
  850. }
  851. string whereSql = sb.ToString();
  852. int count = _db.Updateable(dt).AS(tableName).Where(whereSql, new { id }).ExecuteCommand();
  853. return count;
  854. }
  855. /// <summary>
  856. /// 更新单表,支持同表多条记录
  857. /// </summary>
  858. /// <param name="tableName"></param>
  859. /// <param name="records"></param>
  860. /// <param name="role"></param>
  861. /// <returns></returns>
  862. public int UpdateSingleTable(string tableName, JToken records, APIJSON_Role role = null)
  863. {
  864. role ??= _identitySvc.GetRole();
  865. int count =0;
  866. if (records is JArray)//遍历每行记录
  867. {
  868. foreach (var record in records.ToObject<JObject[]>())
  869. {
  870. count += UpdateSingleRecord(tableName, record, role);
  871. }
  872. }
  873. else//单条记录
  874. {
  875. count = UpdateSingleRecord(tableName, records.ToObject<JObject>(), role);
  876. }
  877. return count;
  878. }
  879. }