Comparison.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //
  2. // Comparison.cs
  3. //
  4. // Author:
  5. // Juraj Skripsky ([email protected])
  6. //
  7. // (C) 2004 HotFeet GmbH (http://www.hotfeet.ch)
  8. //
  9. using System;
  10. using System.Data;
  11. namespace Mono.Data.SqlExpressions {
  12. public class Comparison : BinaryOpExpression {
  13. public Comparison (Operation op, IExpression e1, IExpression e2) : base (op, e1, e2) {}
  14. override public object Eval (DataRow row)
  15. {
  16. IComparable o1 = (IComparable)expr1.Eval (row);
  17. IComparable o2 = (IComparable)expr2.Eval (row);
  18. if (o1 == null || o2 == null) {
  19. if (o1 == null && o2 == null)
  20. return (op == Operation.EQ);
  21. else
  22. return (op == Operation.NE);
  23. }
  24. switch(Compare (o1, o2, row.Table.CaseSensitive)) {
  25. case -1:
  26. return (op == Operation.NE || op == Operation.LE || op == Operation.LT);
  27. case 0:
  28. default:
  29. return (op == Operation.EQ || op == Operation.LE || op == Operation.GE);
  30. case 1:
  31. return (op == Operation.NE || op == Operation.GE || op == Operation.GT);
  32. }
  33. }
  34. internal static int Compare (IComparable o1, IComparable o2, bool caseSensitive)
  35. {
  36. //TODO: turn this "conversion pipeline" into something nicer
  37. try {
  38. if (o1 is string && Numeric.IsNumeric (o2))
  39. o1 = (IComparable)Convert.ChangeType (o1, o2.GetType ());
  40. if (o2 is string && Numeric.IsNumeric (o1))
  41. o2 = (IComparable)Convert.ChangeType (o2, o1.GetType ());
  42. } catch (FormatException) {
  43. throw new EvaluateException (String.Format ("Cannot perform compare operation on {0} and {1}.", o1.GetType(), o2.GetType()));
  44. }
  45. if (o1 is string && o2 is string && !caseSensitive) {
  46. o1 = ((string)o1).ToLower();
  47. o2 = ((string)o2).ToLower();
  48. }
  49. if (o1.GetType () != o2.GetType ())
  50. o2 = (IComparable)Convert.ChangeType (o2, o1.GetType ());
  51. return o1.CompareTo (o2);
  52. }
  53. }
  54. }