SelectTable.cs 37 KB

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