Value.cpp 19 KB

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