SqlGenerator_MethodHandlers.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. using Ant.Core;
  2. using Ant.DbExpressions;
  3. using Ant.ORM;
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.Collections.ObjectModel;
  8. using System.Linq;
  9. using System.Reflection;
  10. using System.Text;
  11. namespace Ant.SQLite
  12. {
  13. partial class SqlGenerator : DbExpressionVisitor<DbExpression>
  14. {
  15. static Dictionary<string, Action<DbMethodCallExpression, SqlGenerator>> InitMethodHandlers()
  16. {
  17. var methodHandlers = new Dictionary<string, Action<DbMethodCallExpression, SqlGenerator>>();
  18. methodHandlers.Add("Trim", Method_Trim);
  19. methodHandlers.Add("TrimStart", Method_TrimStart);
  20. methodHandlers.Add("TrimEnd", Method_TrimEnd);
  21. methodHandlers.Add("StartsWith", Method_StartsWith);
  22. methodHandlers.Add("EndsWith", Method_EndsWith);
  23. methodHandlers.Add("ToUpper", Method_String_ToUpper);
  24. methodHandlers.Add("ToLower", Method_String_ToLower);
  25. methodHandlers.Add("Substring", Method_String_Substring);
  26. methodHandlers.Add("IsNullOrEmpty", Method_String_IsNullOrEmpty);
  27. methodHandlers.Add("Contains", Method_Contains);
  28. methodHandlers.Add("Count", Method_Count);
  29. methodHandlers.Add("LongCount", Method_LongCount);
  30. methodHandlers.Add("Sum", Method_Sum);
  31. methodHandlers.Add("Max", Method_Max);
  32. methodHandlers.Add("Min", Method_Min);
  33. methodHandlers.Add("Average", Method_Average);
  34. methodHandlers.Add("AddYears", Method_DateTime_AddYears);
  35. methodHandlers.Add("AddMonths", Method_DateTime_AddMonths);
  36. methodHandlers.Add("AddDays", Method_DateTime_AddDays);
  37. methodHandlers.Add("AddHours", Method_DateTime_AddHours);
  38. methodHandlers.Add("AddMinutes", Method_DateTime_AddMinutes);
  39. methodHandlers.Add("AddSeconds", Method_DateTime_AddSeconds);
  40. methodHandlers.Add("Parse", Method_Parse);
  41. methodHandlers.Add("NewGuid", Method_Guid_NewGuid);
  42. methodHandlers.Add("DiffYears", Method_DbFunctions_DiffYears);
  43. methodHandlers.Add("DiffMonths", Method_DbFunctions_DiffMonths);
  44. methodHandlers.Add("DiffDays", Method_DbFunctions_DiffDays);
  45. methodHandlers.Add("DiffHours", Method_DbFunctions_DiffHours);
  46. methodHandlers.Add("DiffMinutes", Method_DbFunctions_DiffMinutes);
  47. methodHandlers.Add("DiffSeconds", Method_DbFunctions_DiffSeconds);
  48. methodHandlers.Add("DiffMilliseconds", Method_DbFunctions_DiffMilliseconds);
  49. methodHandlers.Add("DiffMicroseconds", Method_DbFunctions_DiffMicroseconds);
  50. var ret = Utils.Clone(methodHandlers);
  51. return ret;
  52. }
  53. static void Method_Trim(DbMethodCallExpression exp, SqlGenerator generator)
  54. {
  55. EnsureMethod(exp, UtilConstants.MethodInfo_String_Trim);
  56. generator._sqlBuilder.Append("TRIM(");
  57. exp.Object.Accept(generator);
  58. generator._sqlBuilder.Append(")");
  59. }
  60. static void Method_TrimStart(DbMethodCallExpression exp, SqlGenerator generator)
  61. {
  62. EnsureMethod(exp, UtilConstants.MethodInfo_String_TrimStart);
  63. EnsureTrimCharArgumentIsSpaces(exp.Arguments[0]);
  64. generator._sqlBuilder.Append("LTRIM(");
  65. exp.Object.Accept(generator);
  66. generator._sqlBuilder.Append(")");
  67. }
  68. static void Method_TrimEnd(DbMethodCallExpression exp, SqlGenerator generator)
  69. {
  70. EnsureMethod(exp, UtilConstants.MethodInfo_String_TrimEnd);
  71. EnsureTrimCharArgumentIsSpaces(exp.Arguments[0]);
  72. generator._sqlBuilder.Append("RTRIM(");
  73. exp.Object.Accept(generator);
  74. generator._sqlBuilder.Append(")");
  75. }
  76. static void Method_StartsWith(DbMethodCallExpression exp, SqlGenerator generator)
  77. {
  78. EnsureMethod(exp, UtilConstants.MethodInfo_String_StartsWith);
  79. exp.Object.Accept(generator);
  80. generator._sqlBuilder.Append(" LIKE ");
  81. exp.Arguments.First().Accept(generator);
  82. generator._sqlBuilder.Append(" || '%'");
  83. }
  84. static void Method_EndsWith(DbMethodCallExpression exp, SqlGenerator generator)
  85. {
  86. EnsureMethod(exp, UtilConstants.MethodInfo_String_EndsWith);
  87. exp.Object.Accept(generator);
  88. generator._sqlBuilder.Append(" LIKE '%' || ");
  89. exp.Arguments.First().Accept(generator);
  90. }
  91. static void Method_String_Contains(DbMethodCallExpression exp, SqlGenerator generator)
  92. {
  93. EnsureMethod(exp, UtilConstants.MethodInfo_String_Contains);
  94. exp.Object.Accept(generator);
  95. generator._sqlBuilder.Append(" LIKE '%' || ");
  96. exp.Arguments.First().Accept(generator);
  97. generator._sqlBuilder.Append(" || '%'");
  98. }
  99. static void Method_String_ToUpper(DbMethodCallExpression exp, SqlGenerator generator)
  100. {
  101. EnsureMethod(exp, UtilConstants.MethodInfo_String_ToUpper);
  102. generator._sqlBuilder.Append("UPPER(");
  103. exp.Object.Accept(generator);
  104. generator._sqlBuilder.Append(")");
  105. }
  106. static void Method_String_ToLower(DbMethodCallExpression exp, SqlGenerator generator)
  107. {
  108. EnsureMethod(exp, UtilConstants.MethodInfo_String_ToLower);
  109. generator._sqlBuilder.Append("LOWER(");
  110. exp.Object.Accept(generator);
  111. generator._sqlBuilder.Append(")");
  112. }
  113. static void Method_String_Substring(DbMethodCallExpression exp, SqlGenerator generator)
  114. {
  115. generator._sqlBuilder.Append("SUBSTR(");
  116. exp.Object.Accept(generator);
  117. generator._sqlBuilder.Append(",");
  118. exp.Arguments[0].Accept(generator);
  119. generator._sqlBuilder.Append(" + 1");
  120. if (exp.Method == UtilConstants.MethodInfo_String_Substring_Int32)
  121. {
  122. }
  123. else if (exp.Method == UtilConstants.MethodInfo_String_Substring_Int32_Int32)
  124. {
  125. generator._sqlBuilder.Append(",");
  126. exp.Arguments[1].Accept(generator);
  127. }
  128. else
  129. throw UtilExceptions.NotSupportedMethod(exp.Method);
  130. generator._sqlBuilder.Append(")");
  131. }
  132. static void Method_String_IsNullOrEmpty(DbMethodCallExpression exp, SqlGenerator generator)
  133. {
  134. EnsureMethod(exp, UtilConstants.MethodInfo_String_IsNullOrEmpty);
  135. DbExpression e = exp.Arguments.First();
  136. DbEqualExpression equalNullExpression = DbExpression.Equal(e, DbExpression.Constant(null, UtilConstants.TypeOfString));
  137. DbEqualExpression equalEmptyExpression = DbExpression.Equal(e, DbExpression.Constant(string.Empty));
  138. DbOrElseExpression orElseExpression = DbExpression.OrElse(equalNullExpression, equalEmptyExpression);
  139. DbCaseWhenExpression.WhenThenExpressionPair whenThenPair = new DbCaseWhenExpression.WhenThenExpressionPair(orElseExpression, DbConstantExpression.One);
  140. List<DbCaseWhenExpression.WhenThenExpressionPair> whenThenExps = new List<DbCaseWhenExpression.WhenThenExpressionPair>(1);
  141. whenThenExps.Add(whenThenPair);
  142. DbCaseWhenExpression caseWhenExpression = DbExpression.CaseWhen(whenThenExps, DbConstantExpression.Zero, UtilConstants.TypeOfBoolean);
  143. var eqExp = DbExpression.Equal(caseWhenExpression, DbConstantExpression.One);
  144. eqExp.Accept(generator);
  145. }
  146. static void Method_Contains(DbMethodCallExpression exp, SqlGenerator generator)
  147. {
  148. MethodInfo method = exp.Method;
  149. if (method.DeclaringType == UtilConstants.TypeOfString)
  150. {
  151. Method_String_Contains(exp, generator);
  152. return;
  153. }
  154. List<DbExpression> exps = new List<DbExpression>();
  155. IEnumerable values = null;
  156. DbExpression arg = null;
  157. var declaringType = method.DeclaringType;
  158. if (typeof(IList).IsAssignableFrom(declaringType) || (declaringType.IsGenericType && typeof(ICollection<>).MakeGenericType(declaringType.GetGenericArguments()).IsAssignableFrom(declaringType)))
  159. {
  160. DbMemberExpression memberExp = exp.Object as DbMemberExpression;
  161. if (memberExp == null || !memberExp.CanEvaluate())
  162. throw new NotSupportedException(exp.ToString());
  163. values = DbExpressionExtensions.GetExpressionValue(memberExp) as IEnumerable; //Enumerable
  164. arg = exp.Arguments.First();
  165. goto constructInState;
  166. }
  167. if (method.IsStatic && declaringType == typeof(Enumerable) && exp.Arguments.Count == 2)
  168. {
  169. DbMemberExpression memberExp = exp.Arguments.First() as DbMemberExpression;
  170. if (memberExp == null || !memberExp.CanEvaluate())
  171. throw new NotSupportedException(exp.ToString());
  172. values = DbExpressionExtensions.GetExpressionValue(memberExp) as IEnumerable;
  173. arg = exp.Arguments.Skip(1).First();
  174. goto constructInState;
  175. }
  176. throw UtilExceptions.NotSupportedMethod(exp.Method);
  177. constructInState:
  178. foreach (object value in values)
  179. {
  180. if (value == null)
  181. exps.Add(DbExpression.Constant(null, arg.Type));
  182. else
  183. exps.Add(DbExpression.Parameter(value));
  184. }
  185. In(generator, exps, arg);
  186. }
  187. static void In(SqlGenerator generator, List<DbExpression> elementExps, DbExpression arg)
  188. {
  189. if (elementExps.Count == 0)
  190. {
  191. generator._sqlBuilder.Append("1=0");
  192. return;
  193. }
  194. arg.Accept(generator);
  195. generator._sqlBuilder.Append(" IN (");
  196. var first = true;
  197. foreach (DbExpression ele in elementExps)
  198. {
  199. if (first)
  200. first = false;
  201. else
  202. generator._sqlBuilder.Append(",");
  203. ele.Accept(generator);
  204. }
  205. generator._sqlBuilder.Append(")");
  206. return;
  207. }
  208. static void Method_Count(DbMethodCallExpression exp, SqlGenerator generator)
  209. {
  210. EnsureMethodDeclaringType(exp, typeof(AggregateFunctions));
  211. Aggregate_Count(generator);
  212. }
  213. static void Method_LongCount(DbMethodCallExpression exp, SqlGenerator generator)
  214. {
  215. EnsureMethodDeclaringType(exp, typeof(AggregateFunctions));
  216. Aggregate_LongCount(generator);
  217. }
  218. static void Method_Sum(DbMethodCallExpression exp, SqlGenerator generator)
  219. {
  220. EnsureMethodDeclaringType(exp, typeof(AggregateFunctions));
  221. Aggregate_Sum(generator, exp.Arguments.First(), exp.Method.ReturnType);
  222. }
  223. static void Method_Max(DbMethodCallExpression exp, SqlGenerator generator)
  224. {
  225. EnsureMethodDeclaringType(exp, typeof(AggregateFunctions));
  226. Aggregate_Max(generator, exp.Arguments.First(), exp.Method.ReturnType);
  227. }
  228. static void Method_Min(DbMethodCallExpression exp, SqlGenerator generator)
  229. {
  230. EnsureMethodDeclaringType(exp, typeof(AggregateFunctions));
  231. Aggregate_Min(generator, exp.Arguments.First(), exp.Method.ReturnType);
  232. }
  233. static void Method_Average(DbMethodCallExpression exp, SqlGenerator generator)
  234. {
  235. EnsureMethodDeclaringType(exp, typeof(AggregateFunctions));
  236. Aggregate_Average(generator, exp.Arguments.First(), exp.Method.ReturnType);
  237. }
  238. static void Method_DateTime_AddYears(DbMethodCallExpression exp, SqlGenerator generator)
  239. {
  240. EnsureMethodDeclaringType(exp, UtilConstants.TypeOfDateTime);
  241. DbFunction_DATEADD(generator, "years", exp);
  242. }
  243. static void Method_DateTime_AddMonths(DbMethodCallExpression exp, SqlGenerator generator)
  244. {
  245. EnsureMethodDeclaringType(exp, UtilConstants.TypeOfDateTime);
  246. DbFunction_DATEADD(generator, "months", exp);
  247. }
  248. static void Method_DateTime_AddDays(DbMethodCallExpression exp, SqlGenerator generator)
  249. {
  250. EnsureMethodDeclaringType(exp, UtilConstants.TypeOfDateTime);
  251. DbFunction_DATEADD(generator, "days", exp);
  252. }
  253. static void Method_DateTime_AddHours(DbMethodCallExpression exp, SqlGenerator generator)
  254. {
  255. EnsureMethodDeclaringType(exp, UtilConstants.TypeOfDateTime);
  256. DbFunction_DATEADD(generator, "hours", exp);
  257. }
  258. static void Method_DateTime_AddMinutes(DbMethodCallExpression exp, SqlGenerator generator)
  259. {
  260. EnsureMethodDeclaringType(exp, UtilConstants.TypeOfDateTime);
  261. DbFunction_DATEADD(generator, "minutes", exp);
  262. }
  263. static void Method_DateTime_AddSeconds(DbMethodCallExpression exp, SqlGenerator generator)
  264. {
  265. EnsureMethodDeclaringType(exp, UtilConstants.TypeOfDateTime);
  266. DbFunction_DATEADD(generator, "seconds", exp);
  267. }
  268. static void Method_Parse(DbMethodCallExpression exp, SqlGenerator generator)
  269. {
  270. if (exp.Arguments.Count != 1)
  271. throw UtilExceptions.NotSupportedMethod(exp.Method);
  272. DbExpression arg = exp.Arguments[0];
  273. if (arg.Type != UtilConstants.TypeOfString)
  274. throw UtilExceptions.NotSupportedMethod(exp.Method);
  275. Type retType = exp.Method.ReturnType;
  276. EnsureMethodDeclaringType(exp, retType);
  277. DbExpression e = DbExpression.Convert(arg, retType);
  278. e.Accept(generator);
  279. }
  280. static void Method_Guid_NewGuid(DbMethodCallExpression exp, SqlGenerator generator)
  281. {
  282. EnsureMethod(exp, UtilConstants.MethodInfo_Guid_NewGuid);
  283. throw UtilExceptions.NotSupportedMethod(exp.Method);
  284. }
  285. static void Method_DbFunctions_DiffYears(DbMethodCallExpression exp, SqlGenerator generator)
  286. {
  287. EnsureMethod(exp, UtilConstants.MethodInfo_DbFunctions_DiffYears);
  288. Append_DiffYears(generator, exp.Arguments[0], exp.Arguments[1]);
  289. }
  290. static void Method_DbFunctions_DiffMonths(DbMethodCallExpression exp, SqlGenerator generator)
  291. {
  292. EnsureMethod(exp, UtilConstants.MethodInfo_DbFunctions_DiffMonths);
  293. DbExpression startDateTimeExp = exp.Arguments[0];
  294. DbExpression endDateTimeExp = exp.Arguments[1];
  295. /*
  296. * This method will generating sql like following:
  297. (cast(STRFTIME('%Y','2016-07-06 09:01:24') as INTEGER) - cast(STRFTIME('%Y','2015-08-06 09:01:24') as INTEGER)) * 12 + (cast(STRFTIME('%m','2016-07-06 09:01:24') as INTEGER) - cast(STRFTIME('%m','2015-08-06 09:01:24') as INTEGER))
  298. */
  299. generator._sqlBuilder.Append("(");
  300. /* (cast(STRFTIME('%Y','2016-07-06 09:01:24') as INTEGER) - cast(STRFTIME('%Y','2015-08-06 09:01:24') as INTEGER)) * 12 */
  301. Append_DiffYears(generator, startDateTimeExp, endDateTimeExp);
  302. generator._sqlBuilder.Append(" * 12");
  303. generator._sqlBuilder.Append(" + ");
  304. /* (cast(STRFTIME('%m','2016-07-06 09:01:24') as INTEGER) - cast(STRFTIME('%m','2015-08-06 09:01:24') as INTEGER)) */
  305. generator._sqlBuilder.Append("(");
  306. DbFunction_DATEPART(generator, "m", endDateTimeExp);
  307. generator._sqlBuilder.Append(" - ");
  308. DbFunction_DATEPART(generator, "m", startDateTimeExp);
  309. generator._sqlBuilder.Append(")");
  310. generator._sqlBuilder.Append(")");
  311. }
  312. static void Method_DbFunctions_DiffDays(DbMethodCallExpression exp, SqlGenerator generator)
  313. {
  314. EnsureMethod(exp, UtilConstants.MethodInfo_DbFunctions_DiffDays);
  315. Append_DateDiff(generator, exp.Arguments[0], exp.Arguments[1], null);
  316. }
  317. static void Method_DbFunctions_DiffHours(DbMethodCallExpression exp, SqlGenerator generator)
  318. {
  319. EnsureMethod(exp, UtilConstants.MethodInfo_DbFunctions_DiffHours);
  320. Append_DateDiff(generator, exp.Arguments[0], exp.Arguments[1], 24);
  321. }
  322. static void Method_DbFunctions_DiffMinutes(DbMethodCallExpression exp, SqlGenerator generator)
  323. {
  324. EnsureMethod(exp, UtilConstants.MethodInfo_DbFunctions_DiffMinutes);
  325. Append_DateDiff(generator, exp.Arguments[0], exp.Arguments[1], 24 * 60);
  326. }
  327. static void Method_DbFunctions_DiffSeconds(DbMethodCallExpression exp, SqlGenerator generator)
  328. {
  329. EnsureMethod(exp, UtilConstants.MethodInfo_DbFunctions_DiffSeconds);
  330. Append_DateDiff(generator, exp.Arguments[0], exp.Arguments[1], 24 * 60 * 60);
  331. }
  332. static void Method_DbFunctions_DiffMilliseconds(DbMethodCallExpression exp, SqlGenerator generator)
  333. {
  334. EnsureMethod(exp, UtilConstants.MethodInfo_DbFunctions_DiffMilliseconds);
  335. throw UtilExceptions.NotSupportedMethod(exp.Method);
  336. }
  337. static void Method_DbFunctions_DiffMicroseconds(DbMethodCallExpression exp, SqlGenerator generator)
  338. {
  339. EnsureMethod(exp, UtilConstants.MethodInfo_DbFunctions_DiffMicroseconds);
  340. throw UtilExceptions.NotSupportedMethod(exp.Method);
  341. }
  342. static void Append_JULIANDAY(SqlGenerator generator, DbExpression startDateTimeExp, DbExpression endDateTimeExp)
  343. {
  344. /* (JULIANDAY(endDateTimeExp)- JULIANDAY(startDateTimeExp)) */
  345. generator._sqlBuilder.Append("(");
  346. generator._sqlBuilder.Append("JULIANDAY(");
  347. endDateTimeExp.Accept(generator);
  348. generator._sqlBuilder.Append(")");
  349. generator._sqlBuilder.Append(" - ");
  350. generator._sqlBuilder.Append("JULIANDAY(");
  351. startDateTimeExp.Accept(generator);
  352. generator._sqlBuilder.Append(")");
  353. generator._sqlBuilder.Append(")");
  354. }
  355. static void Append_DiffYears(SqlGenerator generator, DbExpression startDateTimeExp, DbExpression endDateTimeExp)
  356. {
  357. /* (CAST(STRFTIME('%Y',endDateTimeExp) as INTEGER) - CAST(STRFTIME('%Y',startDateTimeExp) as INTEGER)) */
  358. generator._sqlBuilder.Append("(");
  359. DbFunction_DATEPART(generator, "Y", endDateTimeExp);
  360. generator._sqlBuilder.Append(" - ");
  361. DbFunction_DATEPART(generator, "Y", startDateTimeExp);
  362. generator._sqlBuilder.Append(")");
  363. }
  364. static void Append_DateDiff(SqlGenerator generator, DbExpression startDateTimeExp, DbExpression endDateTimeExp, int? multiplier)
  365. {
  366. /* CAST((JULIANDAY(endDateTimeExp)- JULIANDAY(startDateTimeExp)) AS INTEGER) */
  367. /* OR */
  368. /* CAST((JULIANDAY(endDateTimeExp)- JULIANDAY(startDateTimeExp)) * multiplier AS INTEGER) */
  369. generator._sqlBuilder.Append("CAST(");
  370. Append_JULIANDAY(generator, startDateTimeExp, endDateTimeExp);
  371. if (multiplier != null)
  372. generator._sqlBuilder.Append(" * ", multiplier.Value.ToString());
  373. generator._sqlBuilder.Append(" AS INTEGER)");
  374. }
  375. }
  376. }