SelectTable.cs 35 KB

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