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