SelectTable.cs 31 KB

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