Expression.cpp 9.2 KB

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