Value.cpp 26 KB

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