Value.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  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 <LibIPC/Decoder.h>
  9. #include <LibIPC/Encoder.h>
  10. #include <LibSQL/AST/AST.h>
  11. #include <LibSQL/Serializer.h>
  12. #include <LibSQL/TupleDescriptor.h>
  13. #include <LibSQL/Value.h>
  14. #include <string.h>
  15. namespace SQL {
  16. // We use the upper 4 bits of the encoded type to store extra information about the type. This
  17. // includes if the value is null, and the encoded size of any integer type. Of course, this encoding
  18. // only works if the SQL type itself fits in the lower 4 bits.
  19. enum class SQLTypeWithCount {
  20. #undef __ENUMERATE_SQL_TYPE
  21. #define __ENUMERATE_SQL_TYPE(name, type) type,
  22. ENUMERATE_SQL_TYPES(__ENUMERATE_SQL_TYPE)
  23. #undef __ENUMERATE_SQL_TYPE
  24. Count,
  25. };
  26. static_assert(to_underlying(SQLTypeWithCount::Count) <= 0x0f, "Too many SQL types for current encoding");
  27. // Adding to this list is fine, but changing the order of any value here will result in LibSQL
  28. // becoming unable to read existing .db files. If the order must absolutely be changed, be sure
  29. // to bump Heap::current_version.
  30. enum class TypeData : u8 {
  31. Null = 1 << 4,
  32. Int8 = 2 << 4,
  33. Int16 = 3 << 4,
  34. Int32 = 4 << 4,
  35. Int64 = 5 << 4,
  36. Uint8 = 6 << 4,
  37. Uint16 = 7 << 4,
  38. Uint32 = 8 << 4,
  39. Uint64 = 9 << 4,
  40. };
  41. template<typename Callback>
  42. static decltype(auto) downsize_integer(Integer auto value, Callback&& callback)
  43. {
  44. if constexpr (IsSigned<decltype(value)>) {
  45. if (AK::is_within_range<i8>(value))
  46. return callback(static_cast<i8>(value), TypeData::Int8);
  47. if (AK::is_within_range<i16>(value))
  48. return callback(static_cast<i16>(value), TypeData::Int16);
  49. if (AK::is_within_range<i32>(value))
  50. return callback(static_cast<i32>(value), TypeData::Int32);
  51. return callback(value, TypeData::Int64);
  52. } else {
  53. if (AK::is_within_range<u8>(value))
  54. return callback(static_cast<i8>(value), TypeData::Uint8);
  55. if (AK::is_within_range<u16>(value))
  56. return callback(static_cast<i16>(value), TypeData::Uint16);
  57. if (AK::is_within_range<u32>(value))
  58. return callback(static_cast<i32>(value), TypeData::Uint32);
  59. return callback(value, TypeData::Uint64);
  60. }
  61. }
  62. template<typename Callback>
  63. static decltype(auto) downsize_integer(Value const& value, Callback&& callback)
  64. {
  65. VERIFY(value.is_int());
  66. if (value.value().has<i64>())
  67. return downsize_integer(value.value().get<i64>(), forward<Callback>(callback));
  68. return downsize_integer(value.value().get<u64>(), forward<Callback>(callback));
  69. }
  70. template<typename Callback>
  71. static ResultOr<Value> perform_integer_operation(Value const& lhs, Value const& rhs, Callback&& callback)
  72. {
  73. VERIFY(lhs.is_int());
  74. VERIFY(rhs.is_int());
  75. if (lhs.value().has<i64>()) {
  76. if (auto rhs_value = rhs.to_int<i64>(); rhs_value.has_value())
  77. return callback(lhs.to_int<i64>().value(), rhs_value.value());
  78. } else {
  79. if (auto rhs_value = rhs.to_int<u64>(); rhs_value.has_value())
  80. return callback(lhs.to_int<u64>().value(), rhs_value.value());
  81. }
  82. return Result { SQLCommand::Unknown, SQLErrorCode::IntegerOverflow };
  83. }
  84. Value::Value(SQLType type)
  85. : m_type(type)
  86. {
  87. }
  88. Value::Value(DeprecatedString value)
  89. : m_type(SQLType::Text)
  90. , m_value(move(value))
  91. {
  92. }
  93. Value::Value(double value)
  94. {
  95. if (trunc(value) == value) {
  96. if (AK::is_within_range<i64>(value)) {
  97. m_type = SQLType::Integer;
  98. m_value = static_cast<i64>(value);
  99. return;
  100. }
  101. if (AK::is_within_range<u64>(value)) {
  102. m_type = SQLType::Integer;
  103. m_value = static_cast<u64>(value);
  104. return;
  105. }
  106. }
  107. m_type = SQLType::Float;
  108. m_value = value;
  109. }
  110. Value::Value(NonnullRefPtr<TupleDescriptor> descriptor, Vector<Value> values)
  111. : m_type(SQLType::Tuple)
  112. , m_value(TupleValue { move(descriptor), move(values) })
  113. {
  114. }
  115. Value::Value(Value const& other)
  116. : m_type(other.m_type)
  117. , m_value(other.m_value)
  118. {
  119. }
  120. Value::Value(Value&& other)
  121. : m_type(other.m_type)
  122. , m_value(move(other.m_value))
  123. {
  124. }
  125. Value::~Value() = default;
  126. ResultOr<Value> Value::create_tuple(NonnullRefPtr<TupleDescriptor> descriptor)
  127. {
  128. Vector<Value> values;
  129. TRY(values.try_resize(descriptor->size()));
  130. for (size_t i = 0; i < descriptor->size(); ++i)
  131. values[i].m_type = descriptor->at(i).type;
  132. return Value { move(descriptor), move(values) };
  133. }
  134. ResultOr<Value> Value::create_tuple(Vector<Value> values)
  135. {
  136. auto descriptor = TRY(infer_tuple_descriptor(values));
  137. return Value { move(descriptor), move(values) };
  138. }
  139. SQLType Value::type() const
  140. {
  141. return m_type;
  142. }
  143. StringView Value::type_name() const
  144. {
  145. switch (type()) {
  146. #undef __ENUMERATE_SQL_TYPE
  147. #define __ENUMERATE_SQL_TYPE(name, type) \
  148. case SQLType::type: \
  149. return name##sv;
  150. ENUMERATE_SQL_TYPES(__ENUMERATE_SQL_TYPE)
  151. #undef __ENUMERATE_SQL_TYPE
  152. default:
  153. VERIFY_NOT_REACHED();
  154. }
  155. }
  156. bool Value::is_type_compatible_with(SQLType other_type) const
  157. {
  158. switch (type()) {
  159. case SQLType::Null:
  160. return false;
  161. case SQLType::Integer:
  162. case SQLType::Float:
  163. return other_type == SQLType::Integer || other_type == SQLType::Float;
  164. default:
  165. break;
  166. }
  167. return type() == other_type;
  168. }
  169. bool Value::is_null() const
  170. {
  171. return !m_value.has_value();
  172. }
  173. bool Value::is_int() const
  174. {
  175. return m_value.has_value() && (m_value->has<i64>() || m_value->has<u64>());
  176. }
  177. DeprecatedString Value::to_deprecated_string() const
  178. {
  179. if (is_null())
  180. return "(null)"sv;
  181. return m_value->visit(
  182. [](DeprecatedString const& value) -> DeprecatedString { return value; },
  183. [](Integer auto value) -> DeprecatedString { return DeprecatedString::number(value); },
  184. [](double value) -> DeprecatedString { return DeprecatedString::number(value); },
  185. [](bool value) -> DeprecatedString { return value ? "true"sv : "false"sv; },
  186. [](TupleValue const& value) -> DeprecatedString {
  187. StringBuilder builder;
  188. builder.append('(');
  189. builder.join(',', value.values);
  190. builder.append(')');
  191. return builder.build();
  192. });
  193. }
  194. Optional<double> Value::to_double() const
  195. {
  196. if (is_null())
  197. return {};
  198. return m_value->visit(
  199. [](DeprecatedString const& value) -> Optional<double> {
  200. char* end = nullptr;
  201. double result = strtod(value.characters(), &end);
  202. if (end == value.characters())
  203. return {};
  204. return result;
  205. },
  206. [](Integer auto value) -> Optional<double> { return static_cast<double>(value); },
  207. [](double value) -> Optional<double> { return value; },
  208. [](bool value) -> Optional<double> { return static_cast<double>(value); },
  209. [](TupleValue const&) -> Optional<double> { return {}; });
  210. }
  211. Optional<bool> Value::to_bool() const
  212. {
  213. if (is_null())
  214. return {};
  215. return m_value->visit(
  216. [](DeprecatedString const& value) -> Optional<bool> {
  217. if (value.equals_ignoring_case("true"sv) || value.equals_ignoring_case("t"sv))
  218. return true;
  219. if (value.equals_ignoring_case("false"sv) || value.equals_ignoring_case("f"sv))
  220. return false;
  221. return {};
  222. },
  223. [](Integer auto value) -> Optional<bool> { return static_cast<bool>(value); },
  224. [](double value) -> Optional<bool> { return fabs(value) > NumericLimits<double>::epsilon(); },
  225. [](bool value) -> Optional<bool> { return value; },
  226. [](TupleValue const& value) -> Optional<bool> {
  227. for (auto const& element : value.values) {
  228. auto as_bool = element.to_bool();
  229. if (!as_bool.has_value())
  230. return {};
  231. if (!as_bool.value())
  232. return false;
  233. }
  234. return true;
  235. });
  236. }
  237. Optional<Vector<Value>> Value::to_vector() const
  238. {
  239. if (is_null() || (type() != SQLType::Tuple))
  240. return {};
  241. auto const& tuple = m_value->get<TupleValue>();
  242. return tuple.values;
  243. }
  244. Value& Value::operator=(Value value)
  245. {
  246. m_type = value.m_type;
  247. m_value = move(value.m_value);
  248. return *this;
  249. }
  250. Value& Value::operator=(DeprecatedString value)
  251. {
  252. m_type = SQLType::Text;
  253. m_value = move(value);
  254. return *this;
  255. }
  256. Value& Value::operator=(double value)
  257. {
  258. m_type = SQLType::Float;
  259. m_value = value;
  260. return *this;
  261. }
  262. ResultOr<void> Value::assign_tuple(NonnullRefPtr<TupleDescriptor> descriptor)
  263. {
  264. Vector<Value> values;
  265. TRY(values.try_resize(descriptor->size()));
  266. for (size_t i = 0; i < descriptor->size(); ++i)
  267. values[i].m_type = descriptor->at(i).type;
  268. m_type = SQLType::Tuple;
  269. m_value = TupleValue { move(descriptor), move(values) };
  270. return {};
  271. }
  272. ResultOr<void> Value::assign_tuple(Vector<Value> values)
  273. {
  274. if (is_null() || (type() != SQLType::Tuple)) {
  275. auto descriptor = TRY(infer_tuple_descriptor(values));
  276. m_type = SQLType::Tuple;
  277. m_value = TupleValue { move(descriptor), move(values) };
  278. return {};
  279. }
  280. auto& tuple = m_value->get<TupleValue>();
  281. if (values.size() > tuple.descriptor->size())
  282. return Result { SQLCommand::Unknown, SQLErrorCode::InvalidNumberOfValues };
  283. for (size_t i = 0; i < values.size(); ++i) {
  284. if (values[i].type() != tuple.descriptor->at(i).type)
  285. return Result { SQLCommand::Unknown, SQLErrorCode::InvalidType, SQLType_name(values[i].type()) };
  286. }
  287. if (values.size() < tuple.descriptor->size()) {
  288. size_t original_size = values.size();
  289. MUST(values.try_resize(tuple.descriptor->size()));
  290. for (size_t i = original_size; i < values.size(); ++i)
  291. values[i].m_type = tuple.descriptor->at(i).type;
  292. }
  293. m_value = TupleValue { move(tuple.descriptor), move(values) };
  294. return {};
  295. }
  296. size_t Value::length() const
  297. {
  298. if (is_null())
  299. return 0;
  300. // FIXME: This seems to be more of an encoded byte size rather than a length.
  301. return m_value->visit(
  302. [](DeprecatedString const& value) -> size_t { return sizeof(u32) + value.length(); },
  303. [](Integer auto value) -> size_t {
  304. return downsize_integer(value, [](auto integer, auto) {
  305. return sizeof(integer);
  306. });
  307. },
  308. [](double value) -> size_t { return sizeof(value); },
  309. [](bool value) -> size_t { return sizeof(value); },
  310. [](TupleValue const& value) -> size_t {
  311. auto size = value.descriptor->length() + sizeof(u32);
  312. for (auto const& element : value.values)
  313. size += element.length();
  314. return size;
  315. });
  316. }
  317. u32 Value::hash() const
  318. {
  319. if (is_null())
  320. return 0;
  321. return m_value->visit(
  322. [](DeprecatedString const& value) -> u32 { return value.hash(); },
  323. [](Integer auto value) -> u32 {
  324. return downsize_integer(value, [](auto integer, auto) {
  325. if constexpr (sizeof(decltype(integer)) == 8)
  326. return u64_hash(integer);
  327. else
  328. return int_hash(integer);
  329. });
  330. },
  331. [](double) -> u32 { VERIFY_NOT_REACHED(); },
  332. [](bool value) -> u32 { return int_hash(value); },
  333. [](TupleValue const& value) -> u32 {
  334. u32 hash = 0;
  335. for (auto const& element : value.values) {
  336. if (hash == 0)
  337. hash = element.hash();
  338. else
  339. hash = pair_int_hash(hash, element.hash());
  340. }
  341. return hash;
  342. });
  343. }
  344. int Value::compare(Value const& other) const
  345. {
  346. if (is_null())
  347. return -1;
  348. if (other.is_null())
  349. return 1;
  350. return m_value->visit(
  351. [&](DeprecatedString const& value) -> int { return value.view().compare(other.to_deprecated_string()); },
  352. [&](Integer auto value) -> int {
  353. auto casted = other.to_int<IntegerType<decltype(value)>>();
  354. if (!casted.has_value())
  355. return 1;
  356. if (value == *casted)
  357. return 0;
  358. return value < *casted ? -1 : 1;
  359. },
  360. [&](double value) -> int {
  361. auto casted = other.to_double();
  362. if (!casted.has_value())
  363. return 1;
  364. auto diff = value - *casted;
  365. if (fabs(diff) < NumericLimits<double>::epsilon())
  366. return 0;
  367. return diff < 0 ? -1 : 1;
  368. },
  369. [&](bool value) -> int {
  370. auto casted = other.to_bool();
  371. if (!casted.has_value())
  372. return 1;
  373. return value ^ *casted;
  374. },
  375. [&](TupleValue const& value) -> int {
  376. if (other.is_null() || (other.type() != SQLType::Tuple)) {
  377. if (value.values.size() == 1)
  378. return value.values[0].compare(other);
  379. return 1;
  380. }
  381. auto const& other_value = other.m_value->get<TupleValue>();
  382. if (auto result = value.descriptor->compare_ignoring_names(*other_value.descriptor); result != 0)
  383. return 1;
  384. if (value.values.size() != other_value.values.size())
  385. return value.values.size() < other_value.values.size() ? -1 : 1;
  386. for (size_t i = 0; i < value.values.size(); ++i) {
  387. auto result = value.values[i].compare(other_value.values[i]);
  388. if (result == 0)
  389. continue;
  390. if (value.descriptor->at(i).order == Order::Descending)
  391. result = -result;
  392. return result;
  393. }
  394. return 0;
  395. });
  396. }
  397. bool Value::operator==(Value const& value) const
  398. {
  399. return compare(value) == 0;
  400. }
  401. bool Value::operator==(StringView value) const
  402. {
  403. return to_deprecated_string() == value;
  404. }
  405. bool Value::operator==(double value) const
  406. {
  407. return to_double() == value;
  408. }
  409. bool Value::operator!=(Value const& value) const
  410. {
  411. return compare(value) != 0;
  412. }
  413. bool Value::operator<(Value const& value) const
  414. {
  415. return compare(value) < 0;
  416. }
  417. bool Value::operator<=(Value const& value) const
  418. {
  419. return compare(value) <= 0;
  420. }
  421. bool Value::operator>(Value const& value) const
  422. {
  423. return compare(value) > 0;
  424. }
  425. bool Value::operator>=(Value const& value) const
  426. {
  427. return compare(value) >= 0;
  428. }
  429. template<typename Operator>
  430. static Result invalid_type_for_numeric_operator(Operator op)
  431. {
  432. if constexpr (IsSame<Operator, AST::BinaryOperator>)
  433. return { SQLCommand::Unknown, SQLErrorCode::NumericOperatorTypeMismatch, BinaryOperator_name(op) };
  434. else if constexpr (IsSame<Operator, AST::UnaryOperator>)
  435. return { SQLCommand::Unknown, SQLErrorCode::NumericOperatorTypeMismatch, UnaryOperator_name(op) };
  436. else
  437. static_assert(DependentFalse<Operator>);
  438. }
  439. ResultOr<Value> Value::add(Value const& other) const
  440. {
  441. if (is_int() && other.is_int()) {
  442. return perform_integer_operation(*this, other, [](auto lhs, auto rhs) -> ResultOr<Value> {
  443. Checked result { lhs };
  444. result.add(rhs);
  445. if (result.has_overflow())
  446. return Result { SQLCommand::Unknown, SQLErrorCode::IntegerOverflow };
  447. return Value { result.value_unchecked() };
  448. });
  449. }
  450. auto lhs = to_double();
  451. auto rhs = other.to_double();
  452. if (!lhs.has_value() || !rhs.has_value())
  453. return invalid_type_for_numeric_operator(AST::BinaryOperator::Plus);
  454. return Value { lhs.value() + rhs.value() };
  455. }
  456. ResultOr<Value> Value::subtract(Value const& other) const
  457. {
  458. if (is_int() && other.is_int()) {
  459. return perform_integer_operation(*this, other, [](auto lhs, auto rhs) -> ResultOr<Value> {
  460. Checked result { lhs };
  461. result.sub(rhs);
  462. if (result.has_overflow())
  463. return Result { SQLCommand::Unknown, SQLErrorCode::IntegerOverflow };
  464. return Value { result.value_unchecked() };
  465. });
  466. }
  467. auto lhs = to_double();
  468. auto rhs = other.to_double();
  469. if (!lhs.has_value() || !rhs.has_value())
  470. return invalid_type_for_numeric_operator(AST::BinaryOperator::Minus);
  471. return Value { lhs.value() - rhs.value() };
  472. }
  473. ResultOr<Value> Value::multiply(Value const& other) const
  474. {
  475. if (is_int() && other.is_int()) {
  476. return perform_integer_operation(*this, other, [](auto lhs, auto rhs) -> ResultOr<Value> {
  477. Checked result { lhs };
  478. result.mul(rhs);
  479. if (result.has_overflow())
  480. return Result { SQLCommand::Unknown, SQLErrorCode::IntegerOverflow };
  481. return Value { result.value_unchecked() };
  482. });
  483. }
  484. auto lhs = to_double();
  485. auto rhs = other.to_double();
  486. if (!lhs.has_value() || !rhs.has_value())
  487. return invalid_type_for_numeric_operator(AST::BinaryOperator::Multiplication);
  488. return Value { lhs.value() * rhs.value() };
  489. }
  490. ResultOr<Value> Value::divide(Value const& other) const
  491. {
  492. auto lhs = to_double();
  493. auto rhs = other.to_double();
  494. if (!lhs.has_value() || !rhs.has_value())
  495. return invalid_type_for_numeric_operator(AST::BinaryOperator::Division);
  496. if (rhs == 0.0)
  497. return Result { SQLCommand::Unknown, SQLErrorCode::IntegerOverflow };
  498. return Value { lhs.value() / rhs.value() };
  499. }
  500. ResultOr<Value> Value::modulo(Value const& other) const
  501. {
  502. if (!is_int() || !other.is_int())
  503. return invalid_type_for_numeric_operator(AST::BinaryOperator::Modulo);
  504. return perform_integer_operation(*this, other, [](auto lhs, auto rhs) -> ResultOr<Value> {
  505. Checked result { lhs };
  506. result.mod(rhs);
  507. if (result.has_overflow())
  508. return Result { SQLCommand::Unknown, SQLErrorCode::IntegerOverflow };
  509. return Value { result.value_unchecked() };
  510. });
  511. }
  512. ResultOr<Value> Value::negate() const
  513. {
  514. if (type() == SQLType::Integer) {
  515. auto value = to_int<i64>();
  516. if (!value.has_value())
  517. return invalid_type_for_numeric_operator(AST::UnaryOperator::Minus);
  518. return Value { value.value() * -1 };
  519. }
  520. if (type() == SQLType::Float)
  521. return Value { -to_double().value() };
  522. return invalid_type_for_numeric_operator(AST::UnaryOperator::Minus);
  523. }
  524. ResultOr<Value> Value::shift_left(Value const& other) const
  525. {
  526. if (!is_int() || !other.is_int())
  527. return invalid_type_for_numeric_operator(AST::BinaryOperator::ShiftLeft);
  528. return perform_integer_operation(*this, other, [](auto lhs, auto rhs) -> ResultOr<Value> {
  529. using LHS = decltype(lhs);
  530. using RHS = decltype(rhs);
  531. static constexpr auto max_shift = static_cast<RHS>(sizeof(LHS) * 8);
  532. if (rhs < 0 || rhs >= max_shift)
  533. return Result { SQLCommand::Unknown, SQLErrorCode::IntegerOverflow };
  534. return Value { lhs << rhs };
  535. });
  536. }
  537. ResultOr<Value> Value::shift_right(Value const& other) const
  538. {
  539. if (!is_int() || !other.is_int())
  540. return invalid_type_for_numeric_operator(AST::BinaryOperator::ShiftRight);
  541. return perform_integer_operation(*this, other, [](auto lhs, auto rhs) -> ResultOr<Value> {
  542. using LHS = decltype(lhs);
  543. using RHS = decltype(rhs);
  544. static constexpr auto max_shift = static_cast<RHS>(sizeof(LHS) * 8);
  545. if (rhs < 0 || rhs >= max_shift)
  546. return Result { SQLCommand::Unknown, SQLErrorCode::IntegerOverflow };
  547. return Value { lhs >> rhs };
  548. });
  549. }
  550. ResultOr<Value> Value::bitwise_or(Value const& other) const
  551. {
  552. if (!is_int() || !other.is_int())
  553. return invalid_type_for_numeric_operator(AST::BinaryOperator::BitwiseOr);
  554. return perform_integer_operation(*this, other, [](auto lhs, auto rhs) {
  555. return Value { lhs | rhs };
  556. });
  557. }
  558. ResultOr<Value> Value::bitwise_and(Value const& other) const
  559. {
  560. if (!is_int() || !other.is_int())
  561. return invalid_type_for_numeric_operator(AST::BinaryOperator::BitwiseAnd);
  562. return perform_integer_operation(*this, other, [](auto lhs, auto rhs) {
  563. return Value { lhs & rhs };
  564. });
  565. }
  566. ResultOr<Value> Value::bitwise_not() const
  567. {
  568. if (!is_int())
  569. return invalid_type_for_numeric_operator(AST::UnaryOperator::BitwiseNot);
  570. return downsize_integer(*this, [](auto value, auto) {
  571. return Value { ~value };
  572. });
  573. }
  574. static u8 encode_type_flags(Value const& value)
  575. {
  576. auto type_flags = to_underlying(value.type());
  577. if (value.is_null()) {
  578. type_flags |= to_underlying(TypeData::Null);
  579. } else if (value.is_int()) {
  580. downsize_integer(value, [&](auto, auto type_data) {
  581. type_flags |= to_underlying(type_data);
  582. });
  583. }
  584. return type_flags;
  585. }
  586. void Value::serialize(Serializer& serializer) const
  587. {
  588. auto type_flags = encode_type_flags(*this);
  589. serializer.serialize<u8>(type_flags);
  590. if (is_null())
  591. return;
  592. if (is_int()) {
  593. downsize_integer(*this, [&](auto integer, auto) {
  594. serializer.serialize(integer);
  595. });
  596. return;
  597. }
  598. m_value->visit(
  599. [&](TupleValue const& value) {
  600. serializer.serialize<TupleDescriptor>(*value.descriptor);
  601. serializer.serialize(static_cast<u32>(value.values.size()));
  602. for (auto const& element : value.values)
  603. serializer.serialize<Value>(element);
  604. },
  605. [&](auto const& value) { serializer.serialize(value); });
  606. }
  607. void Value::deserialize(Serializer& serializer)
  608. {
  609. auto type_flags = serializer.deserialize<u8>();
  610. auto type_data = static_cast<TypeData>(type_flags & 0xf0);
  611. m_type = static_cast<SQLType>(type_flags & 0x0f);
  612. if (type_data == TypeData::Null)
  613. return;
  614. switch (m_type) {
  615. case SQLType::Null:
  616. VERIFY_NOT_REACHED();
  617. break;
  618. case SQLType::Text:
  619. m_value = serializer.deserialize<DeprecatedString>();
  620. break;
  621. case SQLType::Integer:
  622. switch (type_data) {
  623. case TypeData::Int8:
  624. m_value = static_cast<i64>(serializer.deserialize<i8>(0));
  625. break;
  626. case TypeData::Int16:
  627. m_value = static_cast<i64>(serializer.deserialize<i16>(0));
  628. break;
  629. case TypeData::Int32:
  630. m_value = static_cast<i64>(serializer.deserialize<i32>(0));
  631. break;
  632. case TypeData::Int64:
  633. m_value = static_cast<i64>(serializer.deserialize<i64>(0));
  634. break;
  635. case TypeData::Uint8:
  636. m_value = static_cast<u64>(serializer.deserialize<u8>(0));
  637. break;
  638. case TypeData::Uint16:
  639. m_value = static_cast<u64>(serializer.deserialize<u16>(0));
  640. break;
  641. case TypeData::Uint32:
  642. m_value = static_cast<u64>(serializer.deserialize<u32>(0));
  643. break;
  644. case TypeData::Uint64:
  645. m_value = static_cast<u64>(serializer.deserialize<u64>(0));
  646. break;
  647. default:
  648. VERIFY_NOT_REACHED();
  649. break;
  650. }
  651. break;
  652. case SQLType::Float:
  653. m_value = serializer.deserialize<double>(0.0);
  654. break;
  655. case SQLType::Boolean:
  656. m_value = serializer.deserialize<bool>(false);
  657. break;
  658. case SQLType::Tuple: {
  659. auto descriptor = serializer.adopt_and_deserialize<TupleDescriptor>();
  660. auto size = serializer.deserialize<u32>();
  661. Vector<Value> values;
  662. values.ensure_capacity(size);
  663. for (size_t i = 0; i < size; ++i)
  664. values.unchecked_append(serializer.deserialize<Value>());
  665. m_value = TupleValue { move(descriptor), move(values) };
  666. break;
  667. }
  668. }
  669. }
  670. TupleElementDescriptor Value::descriptor() const
  671. {
  672. return { "", "", "", type(), Order::Ascending };
  673. }
  674. ResultOr<NonnullRefPtr<TupleDescriptor>> Value::infer_tuple_descriptor(Vector<Value> const& values)
  675. {
  676. auto descriptor = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) SQL::TupleDescriptor));
  677. TRY(descriptor->try_ensure_capacity(values.size()));
  678. for (auto const& element : values)
  679. descriptor->unchecked_append({ ""sv, ""sv, ""sv, element.type(), Order::Ascending });
  680. return descriptor;
  681. }
  682. }
  683. template<>
  684. bool IPC::encode(Encoder& encoder, SQL::Value const& value)
  685. {
  686. auto type_flags = encode_type_flags(value);
  687. encoder << type_flags;
  688. if (value.is_null())
  689. return true;
  690. switch (value.type()) {
  691. case SQL::SQLType::Null:
  692. break;
  693. case SQL::SQLType::Text:
  694. encoder << value.to_deprecated_string();
  695. break;
  696. case SQL::SQLType::Integer:
  697. SQL::downsize_integer(value, [&](auto integer, auto) {
  698. encoder << integer;
  699. });
  700. break;
  701. case SQL::SQLType::Float:
  702. encoder << value.to_double().value();
  703. break;
  704. case SQL::SQLType::Boolean:
  705. encoder << value.to_bool().value();
  706. break;
  707. case SQL::SQLType::Tuple:
  708. encoder << value.to_vector().value();
  709. break;
  710. }
  711. return true;
  712. }
  713. template<typename T>
  714. static ErrorOr<void> decode_scalar(IPC::Decoder& decoder, SQL::Value& value)
  715. {
  716. T decoded {};
  717. TRY(decoder.decode(decoded));
  718. value = move(decoded);
  719. return {};
  720. }
  721. template<>
  722. ErrorOr<void> IPC::decode(Decoder& decoder, SQL::Value& value)
  723. {
  724. u8 type_flags { 0 };
  725. TRY(decoder.decode(type_flags));
  726. auto type_data = static_cast<SQL::TypeData>(type_flags & 0xf0);
  727. auto type = static_cast<SQL::SQLType>(type_flags & 0x0f);
  728. if (type_data == SQL::TypeData::Null) {
  729. value = SQL::Value(type);
  730. return {};
  731. }
  732. switch (type) {
  733. case SQL::SQLType::Null:
  734. break;
  735. case SQL::SQLType::Text:
  736. TRY(decode_scalar<DeprecatedString>(decoder, value));
  737. break;
  738. case SQL::SQLType::Integer:
  739. switch (type_data) {
  740. case SQL::TypeData::Int8:
  741. TRY(decode_scalar<i8>(decoder, value));
  742. break;
  743. case SQL::TypeData::Int16:
  744. TRY(decode_scalar<i16>(decoder, value));
  745. break;
  746. case SQL::TypeData::Int32:
  747. TRY(decode_scalar<i32>(decoder, value));
  748. break;
  749. case SQL::TypeData::Int64:
  750. TRY(decode_scalar<i64>(decoder, value));
  751. break;
  752. case SQL::TypeData::Uint8:
  753. TRY(decode_scalar<u8>(decoder, value));
  754. break;
  755. case SQL::TypeData::Uint16:
  756. TRY(decode_scalar<u16>(decoder, value));
  757. break;
  758. case SQL::TypeData::Uint32:
  759. TRY(decode_scalar<u32>(decoder, value));
  760. break;
  761. case SQL::TypeData::Uint64:
  762. TRY(decode_scalar<u64>(decoder, value));
  763. break;
  764. default:
  765. VERIFY_NOT_REACHED();
  766. break;
  767. }
  768. break;
  769. case SQL::SQLType::Float:
  770. TRY(decode_scalar<double>(decoder, value));
  771. break;
  772. case SQL::SQLType::Boolean:
  773. TRY(decode_scalar<bool>(decoder, value));
  774. break;
  775. case SQL::SQLType::Tuple: {
  776. Vector<SQL::Value> tuple;
  777. TRY(decoder.decode(tuple));
  778. if (auto result = value.assign_tuple(move(tuple)); result.is_error())
  779. return Error::from_errno(to_underlying(result.error().error()));
  780. break;
  781. }
  782. }
  783. return {};
  784. }