SelectTable.cs 37 KB

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