Value.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. /*
  2. * Copyright (c) 2021, Jan de Visser <jan@de-visser.net>
  3. * Copyright (c) 2022, Tim Flynn <trflynn89@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/NumericLimits.h>
  8. #include <LibSQL/AST/AST.h>
  9. #include <LibSQL/Serializer.h>
  10. #include <LibSQL/TupleDescriptor.h>
  11. #include <LibSQL/Value.h>
  12. #include <math.h>
  13. #include <string.h>
  14. namespace SQL {
  15. Value::Value(SQLType type)
  16. : m_type(type)
  17. {
  18. }
  19. Value::Value(DeprecatedString value)
  20. : m_type(SQLType::Text)
  21. , m_value(move(value))
  22. {
  23. }
  24. Value::Value(int value)
  25. : m_type(SQLType::Integer)
  26. , m_value(value)
  27. {
  28. }
  29. Value::Value(u32 value)
  30. : m_type(SQLType::Integer)
  31. , m_value(static_cast<int>(value)) // FIXME: Handle signed overflow.
  32. {
  33. }
  34. Value::Value(double value)
  35. : m_type(SQLType::Float)
  36. , m_value(value)
  37. {
  38. }
  39. Value::Value(NonnullRefPtr<TupleDescriptor> descriptor, Vector<Value> values)
  40. : m_type(SQLType::Tuple)
  41. , m_value(TupleValue { move(descriptor), move(values) })
  42. {
  43. }
  44. Value::Value(Value const& other)
  45. : m_type(other.m_type)
  46. , m_value(other.m_value)
  47. {
  48. }
  49. Value::Value(Value&& other)
  50. : m_type(other.m_type)
  51. , m_value(move(other.m_value))
  52. {
  53. }
  54. Value::~Value() = default;
  55. ResultOr<Value> Value::create_tuple(NonnullRefPtr<TupleDescriptor> descriptor)
  56. {
  57. Vector<Value> values;
  58. TRY(values.try_resize(descriptor->size()));
  59. for (size_t i = 0; i < descriptor->size(); ++i)
  60. values[i].m_type = descriptor->at(i).type;
  61. return Value { move(descriptor), move(values) };
  62. }
  63. ResultOr<Value> Value::create_tuple(Vector<Value> values)
  64. {
  65. auto descriptor = TRY(infer_tuple_descriptor(values));
  66. return Value { move(descriptor), move(values) };
  67. }
  68. SQLType Value::type() const
  69. {
  70. return m_type;
  71. }
  72. StringView Value::type_name() const
  73. {
  74. switch (type()) {
  75. #undef __ENUMERATE_SQL_TYPE
  76. #define __ENUMERATE_SQL_TYPE(name, cardinal, type, impl, size) \
  77. case SQLType::type: \
  78. return name##sv;
  79. ENUMERATE_SQL_TYPES(__ENUMERATE_SQL_TYPE)
  80. #undef __ENUMERATE_SQL_TYPE
  81. default:
  82. VERIFY_NOT_REACHED();
  83. }
  84. }
  85. bool Value::is_type_compatible_with(SQLType other_type) const
  86. {
  87. switch (type()) {
  88. case SQLType::Null:
  89. return false;
  90. case SQLType::Integer:
  91. case SQLType::Float:
  92. return other_type == SQLType::Integer || other_type == SQLType::Float;
  93. default:
  94. break;
  95. }
  96. return type() == other_type;
  97. }
  98. bool Value::is_null() const
  99. {
  100. return !m_value.has_value();
  101. }
  102. DeprecatedString Value::to_deprecated_string() const
  103. {
  104. if (is_null())
  105. return "(null)"sv;
  106. return m_value->visit(
  107. [](DeprecatedString const& value) -> DeprecatedString { return value; },
  108. [](int value) -> DeprecatedString { return DeprecatedString::number(value); },
  109. [](double value) -> DeprecatedString { return DeprecatedString::number(value); },
  110. [](bool value) -> DeprecatedString { return value ? "true"sv : "false"sv; },
  111. [](TupleValue const& value) -> DeprecatedString {
  112. StringBuilder builder;
  113. builder.append('(');
  114. builder.join(',', value.values);
  115. builder.append(')');
  116. return builder.build();
  117. });
  118. }
  119. Optional<int> Value::to_int() const
  120. {
  121. if (is_null())
  122. return {};
  123. return m_value->visit(
  124. [](DeprecatedString const& value) -> Optional<int> { return value.to_int(); },
  125. [](int value) -> Optional<int> { return value; },
  126. [](double value) -> Optional<int> {
  127. if (value > static_cast<double>(NumericLimits<int>::max()))
  128. return {};
  129. if (value < static_cast<double>(NumericLimits<int>::min()))
  130. return {};
  131. return static_cast<int>(round(value));
  132. },
  133. [](bool value) -> Optional<int> { return static_cast<int>(value); },
  134. [](TupleValue const&) -> Optional<int> { return {}; });
  135. }
  136. Optional<u32> Value::to_u32() const
  137. {
  138. // FIXME: Handle negative values.
  139. if (auto result = to_int(); result.has_value())
  140. return static_cast<u32>(result.value());
  141. return {};
  142. }
  143. Optional<double> Value::to_double() const
  144. {
  145. if (is_null())
  146. return {};
  147. return m_value->visit(
  148. [](DeprecatedString const& value) -> Optional<double> {
  149. char* end = nullptr;
  150. double result = strtod(value.characters(), &end);
  151. if (end == value.characters())
  152. return {};
  153. return result;
  154. },
  155. [](int value) -> Optional<double> { return static_cast<double>(value); },
  156. [](double value) -> Optional<double> { return value; },
  157. [](bool value) -> Optional<double> { return static_cast<double>(value); },
  158. [](TupleValue const&) -> Optional<double> { return {}; });
  159. }
  160. Optional<bool> Value::to_bool() const
  161. {
  162. if (is_null())
  163. return {};
  164. return m_value->visit(
  165. [](DeprecatedString const& value) -> Optional<bool> {
  166. if (value.equals_ignoring_case("true"sv) || value.equals_ignoring_case("t"sv))
  167. return true;
  168. if (value.equals_ignoring_case("false"sv) || value.equals_ignoring_case("f"sv))
  169. return false;
  170. return {};
  171. },
  172. [](int value) -> Optional<bool> { return static_cast<bool>(value); },
  173. [](double value) -> Optional<bool> { return fabs(value) > NumericLimits<double>::epsilon(); },
  174. [](bool value) -> Optional<bool> { return value; },
  175. [](TupleValue const& value) -> Optional<bool> {
  176. for (auto const& element : value.values) {
  177. auto as_bool = element.to_bool();
  178. if (!as_bool.has_value())
  179. return {};
  180. if (!as_bool.value())
  181. return false;
  182. }
  183. return true;
  184. });
  185. }
  186. Optional<Vector<Value>> Value::to_vector() const
  187. {
  188. if (is_null() || (type() != SQLType::Tuple))
  189. return {};
  190. auto const& tuple = m_value->get<TupleValue>();
  191. return tuple.values;
  192. }
  193. Value& Value::operator=(Value value)
  194. {
  195. m_type = value.m_type;
  196. m_value = move(value.m_value);
  197. return *this;
  198. }
  199. Value& Value::operator=(DeprecatedString value)
  200. {
  201. m_type = SQLType::Text;
  202. m_value = move(value);
  203. return *this;
  204. }
  205. Value& Value::operator=(int value)
  206. {
  207. m_type = SQLType::Integer;
  208. m_value = value;
  209. return *this;
  210. }
  211. Value& Value::operator=(u32 value)
  212. {
  213. m_type = SQLType::Integer;
  214. m_value = static_cast<int>(value); // FIXME: Handle signed overflow.
  215. return *this;
  216. }
  217. Value& Value::operator=(double value)
  218. {
  219. m_type = SQLType::Float;
  220. m_value = value;
  221. return *this;
  222. }
  223. ResultOr<void> Value::assign_tuple(NonnullRefPtr<TupleDescriptor> descriptor)
  224. {
  225. Vector<Value> values;
  226. TRY(values.try_resize(descriptor->size()));
  227. for (size_t i = 0; i < descriptor->size(); ++i)
  228. values[i].m_type = descriptor->at(i).type;
  229. m_type = SQLType::Tuple;
  230. m_value = TupleValue { move(descriptor), move(values) };
  231. return {};
  232. }
  233. ResultOr<void> Value::assign_tuple(Vector<Value> values)
  234. {
  235. if (is_null() || (type() != SQLType::Tuple)) {
  236. auto descriptor = TRY(infer_tuple_descriptor(values));
  237. m_type = SQLType::Tuple;
  238. m_value = TupleValue { move(descriptor), move(values) };
  239. return {};
  240. }
  241. auto& tuple = m_value->get<TupleValue>();
  242. if (values.size() > tuple.descriptor->size())
  243. return Result { SQLCommand::Unknown, SQLErrorCode::InvalidNumberOfValues };
  244. for (size_t i = 0; i < values.size(); ++i) {
  245. if (values[i].type() != tuple.descriptor->at(i).type)
  246. return Result { SQLCommand::Unknown, SQLErrorCode::InvalidType, SQLType_name(values[i].type()) };
  247. }
  248. if (values.size() < tuple.descriptor->size()) {
  249. size_t original_size = values.size();
  250. MUST(values.try_resize(tuple.descriptor->size()));
  251. for (size_t i = original_size; i < values.size(); ++i)
  252. values[i].m_type = tuple.descriptor->at(i).type;
  253. }
  254. m_value = TupleValue { move(tuple.descriptor), move(values) };
  255. return {};
  256. }
  257. size_t Value::length() const
  258. {
  259. if (is_null())
  260. return 0;
  261. // FIXME: This seems to be more of an encoded byte size rather than a length.
  262. return m_value->visit(
  263. [](DeprecatedString const& value) -> size_t { return sizeof(u32) + value.length(); },
  264. [](int value) -> size_t { return sizeof(value); },
  265. [](double value) -> size_t { return sizeof(value); },
  266. [](bool value) -> size_t { return sizeof(value); },
  267. [](TupleValue const& value) -> size_t {
  268. auto size = value.descriptor->length() + sizeof(u32);
  269. for (auto const& element : value.values)
  270. size += element.length();
  271. return size;
  272. });
  273. }
  274. u32 Value::hash() const
  275. {
  276. if (is_null())
  277. return 0;
  278. return m_value->visit(
  279. [](DeprecatedString const& value) -> u32 { return value.hash(); },
  280. [](int value) -> u32 { return int_hash(value); },
  281. [](double) -> u32 { VERIFY_NOT_REACHED(); },
  282. [](bool value) -> u32 { return int_hash(value); },
  283. [](TupleValue const& value) -> u32 {
  284. u32 hash = 0;
  285. for (auto const& element : value.values) {
  286. if (hash == 0)
  287. hash = element.hash();
  288. else
  289. hash = pair_int_hash(hash, element.hash());
  290. }
  291. return hash;
  292. });
  293. }
  294. int Value::compare(Value const& other) const
  295. {
  296. if (is_null())
  297. return -1;
  298. if (other.is_null())
  299. return 1;
  300. return m_value->visit(
  301. [&](DeprecatedString const& value) -> int { return value.view().compare(other.to_deprecated_string()); },
  302. [&](int value) -> int {
  303. auto casted = other.to_int();
  304. if (!casted.has_value())
  305. return 1;
  306. if (value == *casted)
  307. return 0;
  308. return value < *casted ? -1 : 1;
  309. },
  310. [&](double value) -> int {
  311. auto casted = other.to_double();
  312. if (!casted.has_value())
  313. return 1;
  314. auto diff = value - *casted;
  315. if (fabs(diff) < NumericLimits<double>::epsilon())
  316. return 0;
  317. return diff < 0 ? -1 : 1;
  318. },
  319. [&](bool value) -> int {
  320. auto casted = other.to_bool();
  321. if (!casted.has_value())
  322. return 1;
  323. return value ^ *casted;
  324. },
  325. [&](TupleValue const& value) -> int {
  326. if (other.is_null() || (other.type() != SQLType::Tuple)) {
  327. if (value.values.size() == 1)
  328. return value.values[0].compare(other);
  329. return 1;
  330. }
  331. auto const& other_value = other.m_value->get<TupleValue>();
  332. if (auto result = value.descriptor->compare_ignoring_names(*other_value.descriptor); result != 0)
  333. return 1;
  334. if (value.values.size() != other_value.values.size())
  335. return value.values.size() < other_value.values.size() ? -1 : 1;
  336. for (size_t i = 0; i < value.values.size(); ++i) {
  337. auto result = value.values[i].compare(other_value.values[i]);
  338. if (result == 0)
  339. continue;
  340. if (value.descriptor->at(i).order == Order::Descending)
  341. result = -result;
  342. return result;
  343. }
  344. return 0;
  345. });
  346. }
  347. bool Value::operator==(Value const& value) const
  348. {
  349. return compare(value) == 0;
  350. }
  351. bool Value::operator==(StringView value) const
  352. {
  353. return to_deprecated_string() == value;
  354. }
  355. bool Value::operator==(int value) const
  356. {
  357. return to_int() == value;
  358. }
  359. bool Value::operator==(u32 value) const
  360. {
  361. return to_u32() == value;
  362. }
  363. bool Value::operator==(double value) const
  364. {
  365. return to_double() == value;
  366. }
  367. bool Value::operator!=(Value const& value) const
  368. {
  369. return compare(value) != 0;
  370. }
  371. bool Value::operator<(Value const& value) const
  372. {
  373. return compare(value) < 0;
  374. }
  375. bool Value::operator<=(Value const& value) const
  376. {
  377. return compare(value) <= 0;
  378. }
  379. bool Value::operator>(Value const& value) const
  380. {
  381. return compare(value) > 0;
  382. }
  383. bool Value::operator>=(Value const& value) const
  384. {
  385. return compare(value) >= 0;
  386. }
  387. static Result invalid_type_for_numeric_operator(AST::BinaryOperator op)
  388. {
  389. return { SQLCommand::Unknown, SQLErrorCode::NumericOperatorTypeMismatch, BinaryOperator_name(op) };
  390. }
  391. ResultOr<Value> Value::add(Value const& other) const
  392. {
  393. if (auto double_maybe = to_double(); double_maybe.has_value()) {
  394. if (auto other_double_maybe = other.to_double(); other_double_maybe.has_value())
  395. return Value(double_maybe.value() + other_double_maybe.value());
  396. if (auto int_maybe = other.to_int(); int_maybe.has_value())
  397. return Value(double_maybe.value() + (double)int_maybe.value());
  398. } else if (auto int_maybe = to_int(); int_maybe.has_value()) {
  399. if (auto other_double_maybe = other.to_double(); other_double_maybe.has_value())
  400. return Value(other_double_maybe.value() + (double)int_maybe.value());
  401. if (auto other_int_maybe = other.to_int(); other_int_maybe.has_value())
  402. return Value(int_maybe.value() + other_int_maybe.value());
  403. }
  404. return invalid_type_for_numeric_operator(AST::BinaryOperator::Plus);
  405. }
  406. ResultOr<Value> Value::subtract(Value const& other) const
  407. {
  408. if (auto double_maybe = to_double(); double_maybe.has_value()) {
  409. if (auto other_double_maybe = other.to_double(); other_double_maybe.has_value())
  410. return Value(double_maybe.value() - other_double_maybe.value());
  411. if (auto int_maybe = other.to_int(); int_maybe.has_value())
  412. return Value(double_maybe.value() - (double)int_maybe.value());
  413. } else if (auto int_maybe = to_int(); int_maybe.has_value()) {
  414. if (auto other_double_maybe = other.to_double(); other_double_maybe.has_value())
  415. return Value((double)int_maybe.value() - other_double_maybe.value());
  416. if (auto other_int_maybe = other.to_int(); other_int_maybe.has_value())
  417. return Value(int_maybe.value() - other_int_maybe.value());
  418. }
  419. return invalid_type_for_numeric_operator(AST::BinaryOperator::Minus);
  420. }
  421. ResultOr<Value> Value::multiply(Value const& other) const
  422. {
  423. if (auto double_maybe = to_double(); double_maybe.has_value()) {
  424. if (auto other_double_maybe = other.to_double(); other_double_maybe.has_value())
  425. return Value(double_maybe.value() * other_double_maybe.value());
  426. if (auto int_maybe = other.to_int(); int_maybe.has_value())
  427. return Value(double_maybe.value() * (double)int_maybe.value());
  428. } else if (auto int_maybe = to_int(); int_maybe.has_value()) {
  429. if (auto other_double_maybe = other.to_double(); other_double_maybe.has_value())
  430. return Value((double)int_maybe.value() * other_double_maybe.value());
  431. if (auto other_int_maybe = other.to_int(); other_int_maybe.has_value())
  432. return Value(int_maybe.value() * other_int_maybe.value());
  433. }
  434. return invalid_type_for_numeric_operator(AST::BinaryOperator::Multiplication);
  435. }
  436. ResultOr<Value> Value::divide(Value const& other) const
  437. {
  438. if (auto double_maybe = to_double(); double_maybe.has_value()) {
  439. if (auto other_double_maybe = other.to_double(); other_double_maybe.has_value())
  440. return Value(double_maybe.value() / other_double_maybe.value());
  441. if (auto int_maybe = other.to_int(); int_maybe.has_value())
  442. return Value(double_maybe.value() / (double)int_maybe.value());
  443. } else if (auto int_maybe = to_int(); int_maybe.has_value()) {
  444. if (auto other_double_maybe = other.to_double(); other_double_maybe.has_value())
  445. return Value((double)int_maybe.value() / other_double_maybe.value());
  446. if (auto other_int_maybe = other.to_int(); other_int_maybe.has_value())
  447. return Value(int_maybe.value() / other_int_maybe.value());
  448. }
  449. return invalid_type_for_numeric_operator(AST::BinaryOperator::Division);
  450. }
  451. ResultOr<Value> Value::modulo(Value const& other) const
  452. {
  453. auto int_maybe_1 = to_int();
  454. auto int_maybe_2 = other.to_int();
  455. if (!int_maybe_1.has_value() || !int_maybe_2.has_value())
  456. return invalid_type_for_numeric_operator(AST::BinaryOperator::Modulo);
  457. return Value(int_maybe_1.value() % int_maybe_2.value());
  458. }
  459. ResultOr<Value> Value::shift_left(Value const& other) const
  460. {
  461. auto u32_maybe = to_u32();
  462. auto num_bytes_maybe = other.to_int();
  463. if (!u32_maybe.has_value() || !num_bytes_maybe.has_value())
  464. return invalid_type_for_numeric_operator(AST::BinaryOperator::ShiftLeft);
  465. return Value(u32_maybe.value() << num_bytes_maybe.value());
  466. }
  467. ResultOr<Value> Value::shift_right(Value const& other) const
  468. {
  469. auto u32_maybe = to_u32();
  470. auto num_bytes_maybe = other.to_int();
  471. if (!u32_maybe.has_value() || !num_bytes_maybe.has_value())
  472. return invalid_type_for_numeric_operator(AST::BinaryOperator::ShiftRight);
  473. return Value(u32_maybe.value() >> num_bytes_maybe.value());
  474. }
  475. ResultOr<Value> Value::bitwise_or(Value const& other) const
  476. {
  477. auto u32_maybe_1 = to_u32();
  478. auto u32_maybe_2 = other.to_u32();
  479. if (!u32_maybe_1.has_value() || !u32_maybe_2.has_value())
  480. return invalid_type_for_numeric_operator(AST::BinaryOperator::BitwiseOr);
  481. return Value(u32_maybe_1.value() | u32_maybe_2.value());
  482. }
  483. ResultOr<Value> Value::bitwise_and(Value const& other) const
  484. {
  485. auto u32_maybe_1 = to_u32();
  486. auto u32_maybe_2 = other.to_u32();
  487. if (!u32_maybe_1.has_value() || !u32_maybe_2.has_value())
  488. return invalid_type_for_numeric_operator(AST::BinaryOperator::BitwiseAnd);
  489. return Value(u32_maybe_1.value() & u32_maybe_2.value());
  490. }
  491. static constexpr auto sql_type_null_as_flag = static_cast<u8>(SQLType::Null);
  492. void Value::serialize(Serializer& serializer) const
  493. {
  494. auto type_flags = static_cast<u8>(type());
  495. if (is_null())
  496. type_flags |= sql_type_null_as_flag;
  497. serializer.serialize<u8>(type_flags);
  498. if (is_null())
  499. return;
  500. m_value->visit(
  501. [&](TupleValue const& value) {
  502. serializer.serialize<TupleDescriptor>(*value.descriptor);
  503. serializer.serialize(static_cast<u32>(value.values.size()));
  504. for (auto const& element : value.values)
  505. serializer.serialize<Value>(element);
  506. },
  507. [&](auto const& value) { serializer.serialize(value); });
  508. }
  509. void Value::deserialize(Serializer& serializer)
  510. {
  511. auto type_flags = serializer.deserialize<u8>();
  512. bool has_value = true;
  513. if ((type_flags & sql_type_null_as_flag) && (type_flags != sql_type_null_as_flag)) {
  514. type_flags &= ~sql_type_null_as_flag;
  515. has_value = false;
  516. }
  517. m_type = static_cast<SQLType>(type_flags);
  518. if (!has_value)
  519. return;
  520. switch (m_type) {
  521. case SQLType::Null:
  522. VERIFY_NOT_REACHED();
  523. break;
  524. case SQLType::Text:
  525. m_value = serializer.deserialize<DeprecatedString>();
  526. break;
  527. case SQLType::Integer:
  528. m_value = serializer.deserialize<int>(0);
  529. break;
  530. case SQLType::Float:
  531. m_value = serializer.deserialize<double>(0.0);
  532. break;
  533. case SQLType::Boolean:
  534. m_value = serializer.deserialize<bool>(false);
  535. break;
  536. case SQLType::Tuple: {
  537. auto descriptor = serializer.adopt_and_deserialize<TupleDescriptor>();
  538. auto size = serializer.deserialize<u32>();
  539. Vector<Value> values;
  540. values.ensure_capacity(size);
  541. for (size_t i = 0; i < size; ++i)
  542. values.unchecked_append(serializer.deserialize<Value>());
  543. m_value = TupleValue { move(descriptor), move(values) };
  544. break;
  545. }
  546. }
  547. }
  548. TupleElementDescriptor Value::descriptor() const
  549. {
  550. return { "", "", "", type(), Order::Ascending };
  551. }
  552. ResultOr<NonnullRefPtr<TupleDescriptor>> Value::infer_tuple_descriptor(Vector<Value> const& values)
  553. {
  554. auto descriptor = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) SQL::TupleDescriptor));
  555. TRY(descriptor->try_ensure_capacity(values.size()));
  556. for (auto const& element : values)
  557. descriptor->unchecked_append({ ""sv, ""sv, ""sv, element.type(), Order::Ascending });
  558. return descriptor;
  559. }
  560. }