Expression.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. /*
  2. * Copyright (c) 2021, Jan de Visser <jan@de-visser.net>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibRegex/Regex.h>
  7. #include <LibSQL/AST/AST.h>
  8. #include <LibSQL/Database.h>
  9. namespace SQL::AST {
  10. static const String s_posix_basic_metacharacters = ".^$*[]+\\";
  11. ResultOr<Value> Expression::evaluate(ExecutionContext&) const
  12. {
  13. return Value::null();
  14. }
  15. ResultOr<Value> NumericLiteral::evaluate(ExecutionContext&) const
  16. {
  17. Value ret(SQLType::Float);
  18. ret = value();
  19. return ret;
  20. }
  21. ResultOr<Value> StringLiteral::evaluate(ExecutionContext&) const
  22. {
  23. Value ret(SQLType::Text);
  24. ret = value();
  25. return ret;
  26. }
  27. ResultOr<Value> NullLiteral::evaluate(ExecutionContext&) const
  28. {
  29. return Value::null();
  30. }
  31. ResultOr<Value> NestedExpression::evaluate(ExecutionContext& context) const
  32. {
  33. return expression()->evaluate(context);
  34. }
  35. ResultOr<Value> ChainedExpression::evaluate(ExecutionContext& context) const
  36. {
  37. Value ret(SQLType::Tuple);
  38. Vector<Value> values;
  39. for (auto& expression : expressions())
  40. values.append(TRY(expression.evaluate(context)));
  41. ret = values;
  42. return ret;
  43. }
  44. ResultOr<Value> BinaryOperatorExpression::evaluate(ExecutionContext& context) const
  45. {
  46. Value lhs_value = TRY(lhs()->evaluate(context));
  47. Value rhs_value = TRY(rhs()->evaluate(context));
  48. switch (type()) {
  49. case BinaryOperator::Concatenate: {
  50. if (lhs_value.type() != SQLType::Text)
  51. return Result { SQLCommand::Unknown, SQLErrorCode::BooleanOperatorTypeMismatch, BinaryOperator_name(type()) };
  52. AK::StringBuilder builder;
  53. builder.append(lhs_value.to_string());
  54. builder.append(rhs_value.to_string());
  55. return Value(builder.to_string());
  56. }
  57. case BinaryOperator::Multiplication:
  58. return lhs_value.multiply(rhs_value);
  59. case BinaryOperator::Division:
  60. return lhs_value.divide(rhs_value);
  61. case BinaryOperator::Modulo:
  62. return lhs_value.modulo(rhs_value);
  63. case BinaryOperator::Plus:
  64. return lhs_value.add(rhs_value);
  65. case BinaryOperator::Minus:
  66. return lhs_value.subtract(rhs_value);
  67. case BinaryOperator::ShiftLeft:
  68. return lhs_value.shift_left(rhs_value);
  69. case BinaryOperator::ShiftRight:
  70. return lhs_value.shift_right(rhs_value);
  71. case BinaryOperator::BitwiseAnd:
  72. return lhs_value.bitwise_and(rhs_value);
  73. case BinaryOperator::BitwiseOr:
  74. return lhs_value.bitwise_or(rhs_value);
  75. case BinaryOperator::LessThan:
  76. return Value(lhs_value.compare(rhs_value) < 0);
  77. case BinaryOperator::LessThanEquals:
  78. return Value(lhs_value.compare(rhs_value) <= 0);
  79. case BinaryOperator::GreaterThan:
  80. return Value(lhs_value.compare(rhs_value) > 0);
  81. case BinaryOperator::GreaterThanEquals:
  82. return Value(lhs_value.compare(rhs_value) >= 0);
  83. case BinaryOperator::Equals:
  84. return Value(lhs_value.compare(rhs_value) == 0);
  85. case BinaryOperator::NotEquals:
  86. return Value(lhs_value.compare(rhs_value) != 0);
  87. case BinaryOperator::And: {
  88. auto lhs_bool_maybe = lhs_value.to_bool();
  89. auto rhs_bool_maybe = rhs_value.to_bool();
  90. if (!lhs_bool_maybe.has_value() || !rhs_bool_maybe.has_value())
  91. return Result { SQLCommand::Unknown, SQLErrorCode::BooleanOperatorTypeMismatch, BinaryOperator_name(type()) };
  92. return Value(lhs_bool_maybe.release_value() && rhs_bool_maybe.release_value());
  93. }
  94. case BinaryOperator::Or: {
  95. auto lhs_bool_maybe = lhs_value.to_bool();
  96. auto rhs_bool_maybe = rhs_value.to_bool();
  97. if (!lhs_bool_maybe.has_value() || !rhs_bool_maybe.has_value())
  98. return Result { SQLCommand::Unknown, SQLErrorCode::BooleanOperatorTypeMismatch, BinaryOperator_name(type()) };
  99. return Value(lhs_bool_maybe.release_value() || rhs_bool_maybe.release_value());
  100. }
  101. default:
  102. VERIFY_NOT_REACHED();
  103. }
  104. }
  105. ResultOr<Value> UnaryOperatorExpression::evaluate(ExecutionContext& context) const
  106. {
  107. Value expression_value = TRY(NestedExpression::evaluate(context));
  108. switch (type()) {
  109. case UnaryOperator::Plus:
  110. if (expression_value.type() == SQLType::Integer || expression_value.type() == SQLType::Float)
  111. return expression_value;
  112. return Result { SQLCommand::Unknown, SQLErrorCode::NumericOperatorTypeMismatch, UnaryOperator_name(type()) };
  113. case UnaryOperator::Minus:
  114. if (expression_value.type() == SQLType::Integer) {
  115. expression_value = -int(expression_value);
  116. return expression_value;
  117. }
  118. if (expression_value.type() == SQLType::Float) {
  119. expression_value = -double(expression_value);
  120. return expression_value;
  121. }
  122. return Result { SQLCommand::Unknown, SQLErrorCode::NumericOperatorTypeMismatch, UnaryOperator_name(type()) };
  123. case UnaryOperator::Not:
  124. if (expression_value.type() == SQLType::Boolean) {
  125. expression_value = !bool(expression_value);
  126. return expression_value;
  127. }
  128. return Result { SQLCommand::Unknown, SQLErrorCode::BooleanOperatorTypeMismatch, UnaryOperator_name(type()) };
  129. case UnaryOperator::BitwiseNot:
  130. if (expression_value.type() == SQLType::Integer) {
  131. expression_value = ~u32(expression_value);
  132. return expression_value;
  133. }
  134. return Result { SQLCommand::Unknown, SQLErrorCode::IntegerOperatorTypeMismatch, UnaryOperator_name(type()) };
  135. default:
  136. VERIFY_NOT_REACHED();
  137. }
  138. }
  139. ResultOr<Value> ColumnNameExpression::evaluate(ExecutionContext& context) const
  140. {
  141. if (!context.current_row)
  142. return Result { SQLCommand::Unknown, SQLErrorCode::SyntaxError, column_name() };
  143. auto& descriptor = *context.current_row->descriptor();
  144. VERIFY(context.current_row->size() == descriptor.size());
  145. Optional<size_t> index_in_row;
  146. for (auto ix = 0u; ix < context.current_row->size(); ix++) {
  147. auto& column_descriptor = descriptor[ix];
  148. if (!table_name().is_empty() && column_descriptor.table != table_name())
  149. continue;
  150. if (column_descriptor.name == column_name()) {
  151. if (index_in_row.has_value())
  152. return Result { SQLCommand::Unknown, SQLErrorCode::AmbiguousColumnName, column_name() };
  153. index_in_row = ix;
  154. }
  155. }
  156. if (index_in_row.has_value())
  157. return (*context.current_row)[index_in_row.value()];
  158. return Result { SQLCommand::Unknown, SQLErrorCode::ColumnDoesNotExist, column_name() };
  159. }
  160. ResultOr<Value> MatchExpression::evaluate(ExecutionContext& context) const
  161. {
  162. switch (type()) {
  163. case MatchOperator::Like: {
  164. Value lhs_value = TRY(lhs()->evaluate(context));
  165. Value rhs_value = TRY(rhs()->evaluate(context));
  166. char escape_char = '\0';
  167. if (escape()) {
  168. auto escape_str = TRY(escape()->evaluate(context)).to_string();
  169. if (escape_str.length() != 1)
  170. return Result { SQLCommand::Unknown, SQLErrorCode::SyntaxError, "ESCAPE should be a single character" };
  171. escape_char = escape_str[0];
  172. }
  173. // Compile the pattern into a simple regex.
  174. // https://sqlite.org/lang_expr.html#the_like_glob_regexp_and_match_operators
  175. bool escaped = false;
  176. AK::StringBuilder builder;
  177. builder.append('^');
  178. for (auto c : rhs_value.to_string()) {
  179. if (escape() && c == escape_char && !escaped) {
  180. escaped = true;
  181. } else if (s_posix_basic_metacharacters.contains(c)) {
  182. escaped = false;
  183. builder.append('\\');
  184. builder.append(c);
  185. } else if (c == '_' && !escaped) {
  186. builder.append('.');
  187. } else if (c == '%' && !escaped) {
  188. builder.append(".*");
  189. } else {
  190. escaped = false;
  191. builder.append(c);
  192. }
  193. }
  194. builder.append('$');
  195. // FIXME: We should probably cache this regex.
  196. auto regex = Regex<PosixBasic>(builder.build());
  197. auto result = regex.match(lhs_value.to_string(), PosixFlags::Insensitive | PosixFlags::Unicode);
  198. return Value(invert_expression() ? !result.success : result.success);
  199. }
  200. case MatchOperator::Regexp: {
  201. Value lhs_value = TRY(lhs()->evaluate(context));
  202. Value rhs_value = TRY(rhs()->evaluate(context));
  203. auto regex = Regex<PosixExtended>(rhs_value.to_string());
  204. auto err = regex.parser_result.error;
  205. if (err != regex::Error::NoError) {
  206. StringBuilder builder;
  207. builder.append("Regular expression: ");
  208. builder.append(get_error_string(err));
  209. return Result { SQLCommand::Unknown, SQLErrorCode::SyntaxError, builder.build() };
  210. }
  211. auto result = regex.match(lhs_value.to_string(), PosixFlags::Insensitive | PosixFlags::Unicode);
  212. return Value(invert_expression() ? !result.success : result.success);
  213. }
  214. case MatchOperator::Glob:
  215. case MatchOperator::Match:
  216. default:
  217. VERIFY_NOT_REACHED();
  218. }
  219. return Value::null();
  220. }
  221. }