SqlGenerator.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. using Ant.Core;
  2. using Ant.Data;
  3. using Ant.DbExpressions;
  4. using Ant.ORM;
  5. using System;
  6. using System.Collections;
  7. using System.Collections.Generic;
  8. using System.Collections.ObjectModel;
  9. using System.Linq;
  10. using System.Reflection;
  11. using System.Text;
  12. namespace Ant.SQLite
  13. {
  14. partial class SqlGenerator : DbExpressionVisitor<DbExpression>
  15. {
  16. public const string ParameterPrefix = "@P_";
  17. internal ISqlBuilder _sqlBuilder = new SqlBuilder();
  18. List<DbParam> _parameters = new List<DbParam>();
  19. static readonly Dictionary<string, Action<DbMethodCallExpression, SqlGenerator>> MethodHandlers = InitMethodHandlers();
  20. static readonly Dictionary<string, Action<DbAggregateExpression, SqlGenerator>> AggregateHandlers = InitAggregateHandlers();
  21. static readonly Dictionary<MethodInfo, Action<DbBinaryExpression, SqlGenerator>> BinaryWithMethodHandlers = InitBinaryWithMethodHandlers();
  22. static readonly Dictionary<Type, string> CastTypeMap = null;
  23. static readonly List<string> CacheParameterNames = null;
  24. static SqlGenerator()
  25. {
  26. Dictionary<Type, string> castTypeMap = new Dictionary<Type, string>();
  27. castTypeMap.Add(typeof(string), "TEXT");
  28. castTypeMap.Add(typeof(byte), "INTEGER");
  29. castTypeMap.Add(typeof(Int16), "INTEGER");
  30. castTypeMap.Add(typeof(int), "INTEGER");
  31. castTypeMap.Add(typeof(long), "INTEGER");
  32. //castTypeMap.Add(typeof(decimal), "DECIMAL(19,0)");//I think this will be a bug.
  33. castTypeMap.Add(typeof(double), "REAL");
  34. castTypeMap.Add(typeof(float), "REAL");
  35. castTypeMap.Add(typeof(bool), "INTEGER");
  36. //castTypeMap.Add(typeof(DateTime), "DATETIME");
  37. //castTypeMap.Add(typeof(Guid), "UNIQUEIDENTIFIER");
  38. CastTypeMap = Utils.Clone(castTypeMap);
  39. int cacheParameterNameCount = 2 * 12;
  40. List<string> cacheParameterNames = new List<string>(cacheParameterNameCount);
  41. for (int i = 0; i < cacheParameterNameCount; i++)
  42. {
  43. string paramName = ParameterPrefix + i.ToString();
  44. cacheParameterNames.Add(paramName);
  45. }
  46. CacheParameterNames = cacheParameterNames;
  47. }
  48. public ISqlBuilder SqlBuilder { get { return this._sqlBuilder; } }
  49. public List<DbParam> Parameters { get { return this._parameters; } }
  50. public static SqlGenerator CreateInstance()
  51. {
  52. return new SqlGenerator();
  53. }
  54. public override DbExpression Visit(DbEqualExpression exp)
  55. {
  56. DbExpression left = exp.Left;
  57. DbExpression right = exp.Right;
  58. left = DbExpressionExtensions.ParseDbExpression(left);
  59. right = DbExpressionExtensions.ParseDbExpression(right);
  60. //明确 left right 其中一边一定为 null
  61. if (DbExpressionExtensions.AffirmExpressionRetValueIsNull(right))
  62. {
  63. left.Accept(this);
  64. this._sqlBuilder.Append(" IS NULL");
  65. return exp;
  66. }
  67. if (DbExpressionExtensions.AffirmExpressionRetValueIsNull(left))
  68. {
  69. right.Accept(this);
  70. this._sqlBuilder.Append(" IS NULL");
  71. return exp;
  72. }
  73. left.Accept(this);
  74. this._sqlBuilder.Append(" = ");
  75. right.Accept(this);
  76. return exp;
  77. }
  78. public override DbExpression Visit(DbNotEqualExpression exp)
  79. {
  80. DbExpression left = exp.Left;
  81. DbExpression right = exp.Right;
  82. left = DbExpressionExtensions.ParseDbExpression(left);
  83. right = DbExpressionExtensions.ParseDbExpression(right);
  84. //明确 left right 其中一边一定为 null
  85. if (DbExpressionExtensions.AffirmExpressionRetValueIsNull(right))
  86. {
  87. left.Accept(this);
  88. this._sqlBuilder.Append(" IS NOT NULL");
  89. return exp;
  90. }
  91. if (DbExpressionExtensions.AffirmExpressionRetValueIsNull(left))
  92. {
  93. right.Accept(this);
  94. this._sqlBuilder.Append(" IS NOT NULL");
  95. return exp;
  96. }
  97. left.Accept(this);
  98. this._sqlBuilder.Append(" <> ");
  99. right.Accept(this);
  100. return exp;
  101. }
  102. public override DbExpression Visit(DbNotExpression exp)
  103. {
  104. this._sqlBuilder.Append("NOT ");
  105. this._sqlBuilder.Append("(");
  106. exp.Operand.Accept(this);
  107. this._sqlBuilder.Append(")");
  108. return exp;
  109. }
  110. public override DbExpression Visit(DbAndExpression exp)
  111. {
  112. Stack<DbExpression> operands = GatherBinaryExpressionOperand(exp);
  113. this.ConcatOperands(operands, " & ");
  114. return exp;
  115. }
  116. public override DbExpression Visit(DbAndAlsoExpression exp)
  117. {
  118. Stack<DbExpression> operands = GatherBinaryExpressionOperand(exp);
  119. this.ConcatOperands(operands, " AND ");
  120. return exp;
  121. }
  122. public override DbExpression Visit(DbOrExpression exp)
  123. {
  124. Stack<DbExpression> operands = GatherBinaryExpressionOperand(exp);
  125. this.ConcatOperands(operands, " | ");
  126. return exp;
  127. }
  128. public override DbExpression Visit(DbOrElseExpression exp)
  129. {
  130. Stack<DbExpression> operands = GatherBinaryExpressionOperand(exp);
  131. this.ConcatOperands(operands, " OR ");
  132. return exp;
  133. }
  134. // +
  135. public override DbExpression Visit(DbAddExpression exp)
  136. {
  137. MethodInfo method = exp.Method;
  138. if (method != null)
  139. {
  140. Action<DbBinaryExpression, SqlGenerator> handler;
  141. if (BinaryWithMethodHandlers.TryGetValue(method, out handler))
  142. {
  143. handler(exp, this);
  144. return exp;
  145. }
  146. throw UtilExceptions.NotSupportedMethod(exp.Method);
  147. }
  148. Stack<DbExpression> operands = GatherBinaryExpressionOperand(exp);
  149. this.ConcatOperands(operands, " + ");
  150. return exp;
  151. }
  152. // -
  153. public override DbExpression Visit(DbSubtractExpression exp)
  154. {
  155. Stack<DbExpression> operands = GatherBinaryExpressionOperand(exp);
  156. this.ConcatOperands(operands, " - ");
  157. return exp;
  158. }
  159. // *
  160. public override DbExpression Visit(DbMultiplyExpression exp)
  161. {
  162. Stack<DbExpression> operands = GatherBinaryExpressionOperand(exp);
  163. this.ConcatOperands(operands, " * ");
  164. return exp;
  165. }
  166. // /
  167. public override DbExpression Visit(DbDivideExpression exp)
  168. {
  169. Stack<DbExpression> operands = GatherBinaryExpressionOperand(exp);
  170. this.ConcatOperands(operands, " / ");
  171. return exp;
  172. }
  173. // <
  174. public override DbExpression Visit(DbLessThanExpression exp)
  175. {
  176. exp.Left.Accept(this);
  177. this._sqlBuilder.Append(" < ");
  178. exp.Right.Accept(this);
  179. return exp;
  180. }
  181. // <=
  182. public override DbExpression Visit(DbLessThanOrEqualExpression exp)
  183. {
  184. exp.Left.Accept(this);
  185. this._sqlBuilder.Append(" <= ");
  186. exp.Right.Accept(this);
  187. return exp;
  188. }
  189. // >
  190. public override DbExpression Visit(DbGreaterThanExpression exp)
  191. {
  192. exp.Left.Accept(this);
  193. this._sqlBuilder.Append(" > ");
  194. exp.Right.Accept(this);
  195. return exp;
  196. }
  197. // >=
  198. public override DbExpression Visit(DbGreaterThanOrEqualExpression exp)
  199. {
  200. exp.Left.Accept(this);
  201. this._sqlBuilder.Append(" >= ");
  202. exp.Right.Accept(this);
  203. return exp;
  204. }
  205. public override DbExpression Visit(DbAggregateExpression exp)
  206. {
  207. Action<DbAggregateExpression, SqlGenerator> aggregateHandler;
  208. if (!AggregateHandlers.TryGetValue(exp.Method.Name, out aggregateHandler))
  209. {
  210. throw UtilExceptions.NotSupportedMethod(exp.Method);
  211. }
  212. aggregateHandler(exp, this);
  213. return exp;
  214. }
  215. public override DbExpression Visit(DbTableExpression exp)
  216. {
  217. this.QuoteName(exp.Table.Name);
  218. return exp;
  219. }
  220. public override DbExpression Visit(DbColumnAccessExpression exp)
  221. {
  222. this.QuoteName(exp.Table.Name);
  223. this._sqlBuilder.Append(".");
  224. this.QuoteName(exp.Column.Name);
  225. return exp;
  226. }
  227. public override DbExpression Visit(DbFromTableExpression exp)
  228. {
  229. this.AppendTableSegment(exp.Table);
  230. this.VisitDbJoinTableExpressions(exp.JoinTables);
  231. return exp;
  232. }
  233. public override DbExpression Visit(DbJoinTableExpression exp)
  234. {
  235. DbJoinTableExpression joinTablePart = exp;
  236. string joinString = null;
  237. if (joinTablePart.JoinType == JoinType.InnerJoin)
  238. {
  239. joinString = " INNER JOIN ";
  240. }
  241. else if (joinTablePart.JoinType == JoinType.LeftJoin)
  242. {
  243. joinString = " LEFT JOIN ";
  244. }
  245. else
  246. throw new NotSupportedException("JoinType: " + joinTablePart.JoinType);
  247. this._sqlBuilder.Append(joinString);
  248. this.AppendTableSegment(joinTablePart.Table);
  249. this._sqlBuilder.Append(" ON ");
  250. joinTablePart.Condition.Accept(this);
  251. this.VisitDbJoinTableExpressions(joinTablePart.JoinTables);
  252. return exp;
  253. }
  254. public override DbExpression Visit(DbSubQueryExpression exp)
  255. {
  256. this._sqlBuilder.Append("(");
  257. exp.SqlQuery.Accept(this);
  258. this._sqlBuilder.Append(")");
  259. return exp;
  260. }
  261. public override DbExpression Visit(DbSqlQueryExpression exp)
  262. {
  263. this.BuildGeneralSql(exp);
  264. return exp;
  265. }
  266. public override DbExpression Visit(DbInsertExpression exp)
  267. {
  268. this._sqlBuilder.Append("INSERT INTO ");
  269. this.QuoteName(exp.Table.Name);
  270. this._sqlBuilder.Append("(");
  271. bool first = true;
  272. foreach (var item in exp.InsertColumns)
  273. {
  274. if (first)
  275. first = false;
  276. else
  277. {
  278. this._sqlBuilder.Append(",");
  279. }
  280. this.QuoteName(item.Key.Name);
  281. }
  282. this._sqlBuilder.Append(")");
  283. this._sqlBuilder.Append(" VALUES(");
  284. first = true;
  285. foreach (var item in exp.InsertColumns)
  286. {
  287. if (first)
  288. first = false;
  289. else
  290. {
  291. this._sqlBuilder.Append(",");
  292. }
  293. item.Value.Accept(this);
  294. }
  295. this._sqlBuilder.Append(")");
  296. return exp;
  297. }
  298. public override DbExpression Visit(DbUpdateExpression exp)
  299. {
  300. this._sqlBuilder.Append("UPDATE ");
  301. this.QuoteName(exp.Table.Name);
  302. this._sqlBuilder.Append(" SET ");
  303. bool first = true;
  304. foreach (var item in exp.UpdateColumns)
  305. {
  306. if (first)
  307. first = false;
  308. else
  309. this._sqlBuilder.Append(",");
  310. this.QuoteName(item.Key.Name);
  311. this._sqlBuilder.Append("=");
  312. item.Value.Accept(this);
  313. }
  314. this.BuildWhereState(exp.Condition);
  315. return exp;
  316. }
  317. public override DbExpression Visit(DbDeleteExpression exp)
  318. {
  319. this._sqlBuilder.Append("DELETE FROM ");
  320. this.QuoteName(exp.Table.Name);
  321. this.BuildWhereState(exp.Condition);
  322. return exp;
  323. }
  324. public override DbExpression Visit(DbCaseWhenExpression exp)
  325. {
  326. this._sqlBuilder.Append("CASE");
  327. foreach (var whenThen in exp.WhenThenPairs)
  328. {
  329. this._sqlBuilder.Append(" WHEN ");
  330. whenThen.When.Accept(this);
  331. this._sqlBuilder.Append(" THEN ");
  332. whenThen.Then.Accept(this);
  333. }
  334. this._sqlBuilder.Append(" ELSE ");
  335. exp.Else.Accept(this);
  336. this._sqlBuilder.Append(" END");
  337. return exp;
  338. }
  339. public override DbExpression Visit(DbConvertExpression exp)
  340. {
  341. DbExpression stripedExp = DbExpressionHelper.StripInvalidConvert(exp);
  342. if (stripedExp.NodeType != DbExpressionType.Convert)
  343. {
  344. stripedExp.Accept(this);
  345. return exp;
  346. }
  347. exp = (DbConvertExpression)stripedExp;
  348. string dbTypeString;
  349. if (TryGetCastTargetDbTypeString(exp.Operand.Type, exp.Type, out dbTypeString, false))
  350. {
  351. this.BuildCastState(exp.Operand, dbTypeString);
  352. }
  353. else
  354. {
  355. Type targetUnType = Utils.GetUnderlyingType(exp.Type);
  356. if (targetUnType == UtilConstants.TypeOfDateTime)
  357. {
  358. /* DATETIME('2016-08-06 09:01:24') */
  359. this._sqlBuilder.Append("DATETIME(");
  360. exp.Operand.Accept(this);
  361. this._sqlBuilder.Append(")");
  362. }
  363. else
  364. exp.Operand.Accept(this);
  365. }
  366. return exp;
  367. }
  368. public override DbExpression Visit(DbMethodCallExpression exp)
  369. {
  370. Action<DbMethodCallExpression, SqlGenerator> methodHandler;
  371. if (!MethodHandlers.TryGetValue(exp.Method.Name, out methodHandler))
  372. {
  373. throw UtilExceptions.NotSupportedMethod(exp.Method);
  374. }
  375. methodHandler(exp, this);
  376. return exp;
  377. }
  378. public override DbExpression Visit(DbMemberExpression exp)
  379. {
  380. MemberInfo member = exp.Member;
  381. if (member.DeclaringType == UtilConstants.TypeOfDateTime)
  382. {
  383. if (member == UtilConstants.PropertyInfo_DateTime_Now)
  384. {
  385. this._sqlBuilder.Append("DATETIME('NOW','LOCALTIME')");
  386. return exp;
  387. }
  388. if (member == UtilConstants.PropertyInfo_DateTime_UtcNow)
  389. {
  390. this._sqlBuilder.Append("DATETIME()");
  391. return exp;
  392. }
  393. if (member == UtilConstants.PropertyInfo_DateTime_Today)
  394. {
  395. this._sqlBuilder.Append("DATE('NOW','LOCALTIME')");
  396. return exp;
  397. }
  398. if (member == UtilConstants.PropertyInfo_DateTime_Date)
  399. {
  400. this._sqlBuilder.Append("DATETIME(DATE(");
  401. exp.Expression.Accept(this);
  402. this._sqlBuilder.Append("))");
  403. return exp;
  404. }
  405. if (IsDbFunction_DATEPART(exp))
  406. {
  407. return exp;
  408. }
  409. }
  410. DbParameterExpression newExp;
  411. if (DbExpressionExtensions.TryParseToParameterExpression(exp, out newExp))
  412. {
  413. return newExp.Accept(this);
  414. }
  415. if (member.Name == "Length" && member.DeclaringType == UtilConstants.TypeOfString)
  416. {
  417. this._sqlBuilder.Append("LENGTH(");
  418. exp.Expression.Accept(this);
  419. this._sqlBuilder.Append(")");
  420. return exp;
  421. }
  422. else if (member.Name == "Value" && Utils.IsNullable(exp.Expression.Type))
  423. {
  424. exp.Expression.Accept(this);
  425. return exp;
  426. }
  427. throw new NotSupportedException(string.Format("'{0}.{1}' is not supported.", member.DeclaringType.FullName, member.Name));
  428. }
  429. public override DbExpression Visit(DbConstantExpression exp)
  430. {
  431. if (exp.Value == null || exp.Value == DBNull.Value)
  432. {
  433. this._sqlBuilder.Append("NULL");
  434. return exp;
  435. }
  436. var objType = exp.Value.GetType();
  437. if (objType == UtilConstants.TypeOfBoolean)
  438. {
  439. this._sqlBuilder.Append(((bool)exp.Value) ? "1" : "0");
  440. return exp;
  441. }
  442. else if (objType == UtilConstants.TypeOfString)
  443. {
  444. this._sqlBuilder.Append("'", exp.Value, "'");
  445. return exp;
  446. }
  447. else if (objType.IsEnum)
  448. {
  449. this._sqlBuilder.Append(((int)exp.Value).ToString());
  450. return exp;
  451. }
  452. this._sqlBuilder.Append(exp.Value);
  453. return exp;
  454. }
  455. public override DbExpression Visit(DbParameterExpression exp)
  456. {
  457. object paramValue = exp.Value;
  458. Type paramType = exp.Type;
  459. if (paramType.IsEnum)
  460. {
  461. paramType = UtilConstants.TypeOfInt32;
  462. if (paramValue != null)
  463. {
  464. paramValue = (int)paramValue;
  465. }
  466. }
  467. if (paramValue == null)
  468. paramValue = DBNull.Value;
  469. DbParam p;
  470. if (paramValue == DBNull.Value)
  471. {
  472. p = this._parameters.Where(a => Utils.AreEqual(a.Value, paramValue) && a.Type == paramType).FirstOrDefault();
  473. }
  474. else
  475. p = this._parameters.Where(a => Utils.AreEqual(a.Value, paramValue)).FirstOrDefault();
  476. if (p != null)
  477. {
  478. this._sqlBuilder.Append(p.Name);
  479. return exp;
  480. }
  481. string paramName = GenParameterName(this._parameters.Count);
  482. p = DbParam.Create(paramName, paramValue, paramType);
  483. if (paramValue.GetType() == UtilConstants.TypeOfString)
  484. {
  485. if (((string)paramValue).Length <= 4000)
  486. p.Size = 4000;
  487. }
  488. this._parameters.Add(p);
  489. this._sqlBuilder.Append(paramName);
  490. return exp;
  491. }
  492. void AppendTableSegment(DbTableSegment seg)
  493. {
  494. seg.Body.Accept(this);
  495. this._sqlBuilder.Append(" AS ");
  496. this.QuoteName(seg.Alias);
  497. }
  498. internal void AppendColumnSegment(DbColumnSegment seg)
  499. {
  500. seg.Body.Accept(this);
  501. this._sqlBuilder.Append(" AS ");
  502. this.QuoteName(seg.Alias);
  503. }
  504. void AppendOrdering(DbOrdering ordering)
  505. {
  506. if (ordering.OrderType == OrderType.Asc)
  507. {
  508. ordering.Expression.Accept(this);
  509. this._sqlBuilder.Append(" ASC");
  510. return;
  511. }
  512. else if (ordering.OrderType == OrderType.Desc)
  513. {
  514. ordering.Expression.Accept(this);
  515. this._sqlBuilder.Append(" DESC");
  516. return;
  517. }
  518. throw new NotSupportedException("OrderType: " + ordering.OrderType);
  519. }
  520. void VisitDbJoinTableExpressions(List<DbJoinTableExpression> tables)
  521. {
  522. foreach (var table in tables)
  523. {
  524. table.Accept(this);
  525. }
  526. }
  527. void BuildGeneralSql(DbSqlQueryExpression exp)
  528. {
  529. this._sqlBuilder.Append("SELECT ");
  530. List<DbColumnSegment> columns = exp.ColumnSegments;
  531. for (int i = 0; i < columns.Count; i++)
  532. {
  533. DbColumnSegment column = columns[i];
  534. if (i > 0)
  535. this._sqlBuilder.Append(",");
  536. this.AppendColumnSegment(column);
  537. }
  538. this._sqlBuilder.Append(" FROM ");
  539. exp.Table.Accept(this);
  540. this.BuildWhereState(exp.Condition);
  541. this.BuildGroupState(exp);
  542. this.BuildOrderState(exp.Orderings);
  543. if (exp.SkipCount == null && exp.TakeCount == null)
  544. return;
  545. int skipCount = exp.SkipCount ?? 0;
  546. long takeCount = long.MaxValue;
  547. if (exp.TakeCount != null)
  548. takeCount = exp.TakeCount.Value;
  549. this._sqlBuilder.Append(" LIMIT ", takeCount.ToString(), " OFFSET ", skipCount.ToString());
  550. }
  551. void BuildWhereState(DbExpression whereExpression)
  552. {
  553. if (whereExpression != null)
  554. {
  555. this._sqlBuilder.Append(" WHERE ");
  556. whereExpression.Accept(this);
  557. }
  558. }
  559. void BuildOrderState(List<DbOrdering> orderings)
  560. {
  561. if (orderings.Count > 0)
  562. {
  563. this._sqlBuilder.Append(" ORDER BY ");
  564. this.ConcatOrderings(orderings);
  565. }
  566. }
  567. void ConcatOrderings(List<DbOrdering> orderings)
  568. {
  569. for (int i = 0; i < orderings.Count; i++)
  570. {
  571. if (i > 0)
  572. {
  573. this._sqlBuilder.Append(",");
  574. }
  575. this.AppendOrdering(orderings[i]);
  576. }
  577. }
  578. void BuildGroupState(DbSqlQueryExpression exp)
  579. {
  580. var groupSegments = exp.GroupSegments;
  581. if (groupSegments.Count == 0)
  582. return;
  583. this._sqlBuilder.Append(" GROUP BY ");
  584. for (int i = 0; i < groupSegments.Count; i++)
  585. {
  586. if (i > 0)
  587. this._sqlBuilder.Append(",");
  588. groupSegments[i].Accept(this);
  589. }
  590. if (exp.HavingCondition != null)
  591. {
  592. this._sqlBuilder.Append(" HAVING ");
  593. exp.HavingCondition.Accept(this);
  594. }
  595. }
  596. void ConcatOperands(IEnumerable<DbExpression> operands, string connector)
  597. {
  598. this._sqlBuilder.Append("(");
  599. bool first = true;
  600. foreach (DbExpression operand in operands)
  601. {
  602. if (first)
  603. first = false;
  604. else
  605. this._sqlBuilder.Append(connector);
  606. operand.Accept(this);
  607. }
  608. this._sqlBuilder.Append(")");
  609. return;
  610. }
  611. void QuoteName(string name)
  612. {
  613. if (string.IsNullOrEmpty(name))
  614. throw new ArgumentException("name");
  615. this._sqlBuilder.Append("[", name, "]");
  616. }
  617. void BuildCastState(DbExpression castExp, string targetDbTypeString)
  618. {
  619. this._sqlBuilder.Append("CAST(");
  620. castExp.Accept(this);
  621. this._sqlBuilder.Append(" AS ", targetDbTypeString, ")");
  622. }
  623. bool IsDbFunction_DATEPART(DbMemberExpression exp)
  624. {
  625. MemberInfo member = exp.Member;
  626. if (member == UtilConstants.PropertyInfo_DateTime_Year)
  627. {
  628. DbFunction_DATEPART(this, "Y", exp.Expression);
  629. return true;
  630. }
  631. if (member == UtilConstants.PropertyInfo_DateTime_Month)
  632. {
  633. DbFunction_DATEPART(this, "m", exp.Expression);
  634. return true;
  635. }
  636. if (member == UtilConstants.PropertyInfo_DateTime_Day)
  637. {
  638. DbFunction_DATEPART(this, "d", exp.Expression);
  639. return true;
  640. }
  641. if (member == UtilConstants.PropertyInfo_DateTime_Hour)
  642. {
  643. DbFunction_DATEPART(this, "H", exp.Expression);
  644. return true;
  645. }
  646. if (member == UtilConstants.PropertyInfo_DateTime_Minute)
  647. {
  648. DbFunction_DATEPART(this, "M", exp.Expression);
  649. return true;
  650. }
  651. if (member == UtilConstants.PropertyInfo_DateTime_Second)
  652. {
  653. DbFunction_DATEPART(this, "S", exp.Expression);
  654. return true;
  655. }
  656. /* SQLite is not supports MILLISECOND */
  657. if (member == UtilConstants.PropertyInfo_DateTime_DayOfWeek)
  658. {
  659. DbFunction_DATEPART(this, "w", exp.Expression);
  660. return true;
  661. }
  662. return false;
  663. }
  664. #region BinaryWithMethodHandlers
  665. static Dictionary<MethodInfo, Action<DbBinaryExpression, SqlGenerator>> InitBinaryWithMethodHandlers()
  666. {
  667. var binaryWithMethodHandlers = new Dictionary<MethodInfo, Action<DbBinaryExpression, SqlGenerator>>();
  668. binaryWithMethodHandlers.Add(UtilConstants.MethodInfo_String_Concat_String_String, StringConcat);
  669. binaryWithMethodHandlers.Add(UtilConstants.MethodInfo_String_Concat_Object_Object, StringConcat);
  670. var ret = Utils.Clone(binaryWithMethodHandlers);
  671. return ret;
  672. }
  673. static void StringConcat(DbBinaryExpression exp, SqlGenerator generator)
  674. {
  675. MethodInfo method = exp.Method;
  676. List<DbExpression> operands = new List<DbExpression>();
  677. operands.Add(exp.Right);
  678. DbExpression left = exp.Left;
  679. DbAddExpression e = null;
  680. while ((e = (left as DbAddExpression)) != null && (e.Method == UtilConstants.MethodInfo_String_Concat_String_String || e.Method == UtilConstants.MethodInfo_String_Concat_Object_Object))
  681. {
  682. operands.Add(e.Right);
  683. left = e.Left;
  684. }
  685. operands.Add(left);
  686. DbExpression whenExp = null;
  687. List<DbExpression> operandExps = new List<DbExpression>(operands.Count);
  688. for (int i = operands.Count - 1; i >= 0; i--)
  689. {
  690. DbExpression operand = operands[i];
  691. DbExpression opBody = operand;
  692. if (opBody.Type != UtilConstants.TypeOfString)
  693. {
  694. // 需要 cast type
  695. opBody = DbExpression.Convert(opBody, UtilConstants.TypeOfString);
  696. }
  697. DbExpression equalNullExp = DbExpression.Equal(opBody, UtilConstants.DbConstant_Null_String);
  698. if (whenExp == null)
  699. whenExp = equalNullExp;
  700. else
  701. whenExp = DbExpression.AndAlso(whenExp, equalNullExp);
  702. DbExpression thenExp = DbConstantExpression.StringEmpty;
  703. DbCaseWhenExpression.WhenThenExpressionPair whenThenPair = new DbCaseWhenExpression.WhenThenExpressionPair(equalNullExp, thenExp);
  704. List<DbCaseWhenExpression.WhenThenExpressionPair> whenThenExps = new List<DbCaseWhenExpression.WhenThenExpressionPair>(1);
  705. whenThenExps.Add(whenThenPair);
  706. DbExpression elseExp = opBody;
  707. DbCaseWhenExpression caseWhenExpression = DbExpression.CaseWhen(whenThenExps, elseExp, UtilConstants.TypeOfString);
  708. operandExps.Add(caseWhenExpression);
  709. }
  710. generator._sqlBuilder.Append("CASE", " WHEN ");
  711. whenExp.Accept(generator);
  712. generator._sqlBuilder.Append(" THEN ");
  713. DbConstantExpression.Null.Accept(generator);
  714. generator._sqlBuilder.Append(" ELSE ");
  715. generator._sqlBuilder.Append("(");
  716. for (int i = 0; i < operandExps.Count; i++)
  717. {
  718. if (i > 0)
  719. generator._sqlBuilder.Append(" || ");
  720. operandExps[i].Accept(generator);
  721. }
  722. generator._sqlBuilder.Append(")");
  723. generator._sqlBuilder.Append(" END");
  724. }
  725. #endregion
  726. }
  727. }