SelectTable.cs 36 KB

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