SelectTable.cs 31 KB

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