Expression.cpp 9.3 KB

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