Expression.cpp 9.2 KB

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