Value.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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> { return value.to_double(); },
  200. [](Integer auto value) -> Optional<double> { return static_cast<double>(value); },
  201. [](double value) -> Optional<double> { return value; },
  202. [](bool value) -> Optional<double> { return static_cast<double>(value); },
  203. [](TupleValue const&) -> Optional<double> { return {}; });
  204. }
  205. Optional<bool> Value::to_bool() const
  206. {
  207. if (is_null())
  208. return {};
  209. return m_value->visit(
  210. [](DeprecatedString const& value) -> Optional<bool> {
  211. if (value.equals_ignoring_case("true"sv) || value.equals_ignoring_case("t"sv))
  212. return true;
  213. if (value.equals_ignoring_case("false"sv) || value.equals_ignoring_case("f"sv))
  214. return false;
  215. return {};
  216. },
  217. [](Integer auto value) -> Optional<bool> { return static_cast<bool>(value); },
  218. [](double value) -> Optional<bool> { return fabs(value) > NumericLimits<double>::epsilon(); },
  219. [](bool value) -> Optional<bool> { return value; },
  220. [](TupleValue const& value) -> Optional<bool> {
  221. for (auto const& element : value.values) {
  222. auto as_bool = element.to_bool();
  223. if (!as_bool.has_value())
  224. return {};
  225. if (!as_bool.value())
  226. return false;
  227. }
  228. return true;
  229. });
  230. }
  231. Optional<Vector<Value>> Value::to_vector() const
  232. {
  233. if (is_null() || (type() != SQLType::Tuple))
  234. return {};
  235. auto const& tuple = m_value->get<TupleValue>();
  236. return tuple.values;
  237. }
  238. Value& Value::operator=(Value value)
  239. {
  240. m_type = value.m_type;
  241. m_value = move(value.m_value);
  242. return *this;
  243. }
  244. Value& Value::operator=(DeprecatedString value)
  245. {
  246. m_type = SQLType::Text;
  247. m_value = move(value);
  248. return *this;
  249. }
  250. Value& Value::operator=(double value)
  251. {
  252. m_type = SQLType::Float;
  253. m_value = value;
  254. return *this;
  255. }
  256. ResultOr<void> Value::assign_tuple(NonnullRefPtr<TupleDescriptor> descriptor)
  257. {
  258. Vector<Value> values;
  259. TRY(values.try_resize(descriptor->size()));
  260. for (size_t i = 0; i < descriptor->size(); ++i)
  261. values[i].m_type = descriptor->at(i).type;
  262. m_type = SQLType::Tuple;
  263. m_value = TupleValue { move(descriptor), move(values) };
  264. return {};
  265. }
  266. ResultOr<void> Value::assign_tuple(Vector<Value> values)
  267. {
  268. if (is_null() || (type() != SQLType::Tuple)) {
  269. auto descriptor = TRY(infer_tuple_descriptor(values));
  270. m_type = SQLType::Tuple;
  271. m_value = TupleValue { move(descriptor), move(values) };
  272. return {};
  273. }
  274. auto& tuple = m_value->get<TupleValue>();
  275. if (values.size() > tuple.descriptor->size())
  276. return Result { SQLCommand::Unknown, SQLErrorCode::InvalidNumberOfValues };
  277. for (size_t i = 0; i < values.size(); ++i) {
  278. if (values[i].type() != tuple.descriptor->at(i).type)
  279. return Result { SQLCommand::Unknown, SQLErrorCode::InvalidType, SQLType_name(values[i].type()) };
  280. }
  281. if (values.size() < tuple.descriptor->size()) {
  282. size_t original_size = values.size();
  283. MUST(values.try_resize(tuple.descriptor->size()));
  284. for (size_t i = original_size; i < values.size(); ++i)
  285. values[i].m_type = tuple.descriptor->at(i).type;
  286. }
  287. m_value = TupleValue { move(tuple.descriptor), move(values) };
  288. return {};
  289. }
  290. size_t Value::length() const
  291. {
  292. if (is_null())
  293. return 0;
  294. // FIXME: This seems to be more of an encoded byte size rather than a length.
  295. return m_value->visit(
  296. [](DeprecatedString const& value) -> size_t { return sizeof(u32) + value.length(); },
  297. [](Integer auto value) -> size_t {
  298. return downsize_integer(value, [](auto integer, auto) {
  299. return sizeof(integer);
  300. });
  301. },
  302. [](double value) -> size_t { return sizeof(value); },
  303. [](bool value) -> size_t { return sizeof(value); },
  304. [](TupleValue const& value) -> size_t {
  305. auto size = value.descriptor->length() + sizeof(u32);
  306. for (auto const& element : value.values)
  307. size += element.length();
  308. return size;
  309. });
  310. }
  311. u32 Value::hash() const
  312. {
  313. if (is_null())
  314. return 0;
  315. return m_value->visit(
  316. [](DeprecatedString const& value) -> u32 { return value.hash(); },
  317. [](Integer auto value) -> u32 {
  318. return downsize_integer(value, [](auto integer, auto) {
  319. if constexpr (sizeof(decltype(integer)) == 8)
  320. return u64_hash(integer);
  321. else
  322. return int_hash(integer);
  323. });
  324. },
  325. [](double) -> u32 { VERIFY_NOT_REACHED(); },
  326. [](bool value) -> u32 { return int_hash(value); },
  327. [](TupleValue const& value) -> u32 {
  328. u32 hash = 0;
  329. for (auto const& element : value.values) {
  330. if (hash == 0)
  331. hash = element.hash();
  332. else
  333. hash = pair_int_hash(hash, element.hash());
  334. }
  335. return hash;
  336. });
  337. }
  338. int Value::compare(Value const& other) const
  339. {
  340. if (is_null())
  341. return -1;
  342. if (other.is_null())
  343. return 1;
  344. return m_value->visit(
  345. [&](DeprecatedString const& value) -> int { return value.view().compare(other.to_deprecated_string()); },
  346. [&](Integer auto value) -> int {
  347. auto casted = other.to_int<IntegerType<decltype(value)>>();
  348. if (!casted.has_value())
  349. return 1;
  350. if (value == *casted)
  351. return 0;
  352. return value < *casted ? -1 : 1;
  353. },
  354. [&](double value) -> int {
  355. auto casted = other.to_double();
  356. if (!casted.has_value())
  357. return 1;
  358. auto diff = value - *casted;
  359. if (fabs(diff) < NumericLimits<double>::epsilon())
  360. return 0;
  361. return diff < 0 ? -1 : 1;
  362. },
  363. [&](bool value) -> int {
  364. auto casted = other.to_bool();
  365. if (!casted.has_value())
  366. return 1;
  367. return value ^ *casted;
  368. },
  369. [&](TupleValue const& value) -> int {
  370. if (other.is_null() || (other.type() != SQLType::Tuple)) {
  371. if (value.values.size() == 1)
  372. return value.values[0].compare(other);
  373. return 1;
  374. }
  375. auto const& other_value = other.m_value->get<TupleValue>();
  376. if (auto result = value.descriptor->compare_ignoring_names(*other_value.descriptor); result != 0)
  377. return 1;
  378. if (value.values.size() != other_value.values.size())
  379. return value.values.size() < other_value.values.size() ? -1 : 1;
  380. for (size_t i = 0; i < value.values.size(); ++i) {
  381. auto result = value.values[i].compare(other_value.values[i]);
  382. if (result == 0)
  383. continue;
  384. if (value.descriptor->at(i).order == Order::Descending)
  385. result = -result;
  386. return result;
  387. }
  388. return 0;
  389. });
  390. }
  391. bool Value::operator==(Value const& value) const
  392. {
  393. return compare(value) == 0;
  394. }
  395. bool Value::operator==(StringView value) const
  396. {
  397. return to_deprecated_string() == value;
  398. }
  399. bool Value::operator==(double value) const
  400. {
  401. return to_double() == value;
  402. }
  403. bool Value::operator!=(Value const& value) const
  404. {
  405. return compare(value) != 0;
  406. }
  407. bool Value::operator<(Value const& value) const
  408. {
  409. return compare(value) < 0;
  410. }
  411. bool Value::operator<=(Value const& value) const
  412. {
  413. return compare(value) <= 0;
  414. }
  415. bool Value::operator>(Value const& value) const
  416. {
  417. return compare(value) > 0;
  418. }
  419. bool Value::operator>=(Value const& value) const
  420. {
  421. return compare(value) >= 0;
  422. }
  423. template<typename Operator>
  424. static Result invalid_type_for_numeric_operator(Operator op)
  425. {
  426. if constexpr (IsSame<Operator, AST::BinaryOperator>)
  427. return { SQLCommand::Unknown, SQLErrorCode::NumericOperatorTypeMismatch, BinaryOperator_name(op) };
  428. else if constexpr (IsSame<Operator, AST::UnaryOperator>)
  429. return { SQLCommand::Unknown, SQLErrorCode::NumericOperatorTypeMismatch, UnaryOperator_name(op) };
  430. else
  431. static_assert(DependentFalse<Operator>);
  432. }
  433. ResultOr<Value> Value::add(Value const& other) const
  434. {
  435. if (is_int() && other.is_int()) {
  436. return perform_integer_operation(*this, other, [](auto lhs, auto rhs) -> ResultOr<Value> {
  437. Checked result { lhs };
  438. result.add(rhs);
  439. if (result.has_overflow())
  440. return Result { SQLCommand::Unknown, SQLErrorCode::IntegerOverflow };
  441. return Value { result.value_unchecked() };
  442. });
  443. }
  444. auto lhs = to_double();
  445. auto rhs = other.to_double();
  446. if (!lhs.has_value() || !rhs.has_value())
  447. return invalid_type_for_numeric_operator(AST::BinaryOperator::Plus);
  448. return Value { lhs.value() + rhs.value() };
  449. }
  450. ResultOr<Value> Value::subtract(Value const& other) const
  451. {
  452. if (is_int() && other.is_int()) {
  453. return perform_integer_operation(*this, other, [](auto lhs, auto rhs) -> ResultOr<Value> {
  454. Checked result { lhs };
  455. result.sub(rhs);
  456. if (result.has_overflow())
  457. return Result { SQLCommand::Unknown, SQLErrorCode::IntegerOverflow };
  458. return Value { result.value_unchecked() };
  459. });
  460. }
  461. auto lhs = to_double();
  462. auto rhs = other.to_double();
  463. if (!lhs.has_value() || !rhs.has_value())
  464. return invalid_type_for_numeric_operator(AST::BinaryOperator::Minus);
  465. return Value { lhs.value() - rhs.value() };
  466. }
  467. ResultOr<Value> Value::multiply(Value const& other) const
  468. {
  469. if (is_int() && other.is_int()) {
  470. return perform_integer_operation(*this, other, [](auto lhs, auto rhs) -> ResultOr<Value> {
  471. Checked result { lhs };
  472. result.mul(rhs);
  473. if (result.has_overflow())
  474. return Result { SQLCommand::Unknown, SQLErrorCode::IntegerOverflow };
  475. return Value { result.value_unchecked() };
  476. });
  477. }
  478. auto lhs = to_double();
  479. auto rhs = other.to_double();
  480. if (!lhs.has_value() || !rhs.has_value())
  481. return invalid_type_for_numeric_operator(AST::BinaryOperator::Multiplication);
  482. return Value { lhs.value() * rhs.value() };
  483. }
  484. ResultOr<Value> Value::divide(Value const& other) const
  485. {
  486. auto lhs = to_double();
  487. auto rhs = other.to_double();
  488. if (!lhs.has_value() || !rhs.has_value())
  489. return invalid_type_for_numeric_operator(AST::BinaryOperator::Division);
  490. if (rhs == 0.0)
  491. return Result { SQLCommand::Unknown, SQLErrorCode::IntegerOverflow };
  492. return Value { lhs.value() / rhs.value() };
  493. }
  494. ResultOr<Value> Value::modulo(Value const& other) const
  495. {
  496. if (!is_int() || !other.is_int())
  497. return invalid_type_for_numeric_operator(AST::BinaryOperator::Modulo);
  498. return perform_integer_operation(*this, other, [](auto lhs, auto rhs) -> ResultOr<Value> {
  499. Checked result { lhs };
  500. result.mod(rhs);
  501. if (result.has_overflow())
  502. return Result { SQLCommand::Unknown, SQLErrorCode::IntegerOverflow };
  503. return Value { result.value_unchecked() };
  504. });
  505. }
  506. ResultOr<Value> Value::negate() const
  507. {
  508. if (type() == SQLType::Integer) {
  509. auto value = to_int<i64>();
  510. if (!value.has_value())
  511. return invalid_type_for_numeric_operator(AST::UnaryOperator::Minus);
  512. return Value { value.value() * -1 };
  513. }
  514. if (type() == SQLType::Float)
  515. return Value { -to_double().value() };
  516. return invalid_type_for_numeric_operator(AST::UnaryOperator::Minus);
  517. }
  518. ResultOr<Value> Value::shift_left(Value const& other) const
  519. {
  520. if (!is_int() || !other.is_int())
  521. return invalid_type_for_numeric_operator(AST::BinaryOperator::ShiftLeft);
  522. return perform_integer_operation(*this, other, [](auto lhs, auto rhs) -> ResultOr<Value> {
  523. using LHS = decltype(lhs);
  524. using RHS = decltype(rhs);
  525. static constexpr auto max_shift = static_cast<RHS>(sizeof(LHS) * 8);
  526. if (rhs < 0 || rhs >= max_shift)
  527. return Result { SQLCommand::Unknown, SQLErrorCode::IntegerOverflow };
  528. return Value { lhs << rhs };
  529. });
  530. }
  531. ResultOr<Value> Value::shift_right(Value const& other) const
  532. {
  533. if (!is_int() || !other.is_int())
  534. return invalid_type_for_numeric_operator(AST::BinaryOperator::ShiftRight);
  535. return perform_integer_operation(*this, other, [](auto lhs, auto rhs) -> ResultOr<Value> {
  536. using LHS = decltype(lhs);
  537. using RHS = decltype(rhs);
  538. static constexpr auto max_shift = static_cast<RHS>(sizeof(LHS) * 8);
  539. if (rhs < 0 || rhs >= max_shift)
  540. return Result { SQLCommand::Unknown, SQLErrorCode::IntegerOverflow };
  541. return Value { lhs >> rhs };
  542. });
  543. }
  544. ResultOr<Value> Value::bitwise_or(Value const& other) const
  545. {
  546. if (!is_int() || !other.is_int())
  547. return invalid_type_for_numeric_operator(AST::BinaryOperator::BitwiseOr);
  548. return perform_integer_operation(*this, other, [](auto lhs, auto rhs) {
  549. return Value { lhs | rhs };
  550. });
  551. }
  552. ResultOr<Value> Value::bitwise_and(Value const& other) const
  553. {
  554. if (!is_int() || !other.is_int())
  555. return invalid_type_for_numeric_operator(AST::BinaryOperator::BitwiseAnd);
  556. return perform_integer_operation(*this, other, [](auto lhs, auto rhs) {
  557. return Value { lhs & rhs };
  558. });
  559. }
  560. ResultOr<Value> Value::bitwise_not() const
  561. {
  562. if (!is_int())
  563. return invalid_type_for_numeric_operator(AST::UnaryOperator::BitwiseNot);
  564. return downsize_integer(*this, [](auto value, auto) {
  565. return Value { ~value };
  566. });
  567. }
  568. static u8 encode_type_flags(Value const& value)
  569. {
  570. auto type_flags = to_underlying(value.type());
  571. if (value.is_null()) {
  572. type_flags |= to_underlying(TypeData::Null);
  573. } else if (value.is_int()) {
  574. downsize_integer(value, [&](auto, auto type_data) {
  575. type_flags |= to_underlying(type_data);
  576. });
  577. }
  578. return type_flags;
  579. }
  580. void Value::serialize(Serializer& serializer) const
  581. {
  582. auto type_flags = encode_type_flags(*this);
  583. serializer.serialize<u8>(type_flags);
  584. if (is_null())
  585. return;
  586. if (is_int()) {
  587. downsize_integer(*this, [&](auto integer, auto) {
  588. serializer.serialize(integer);
  589. });
  590. return;
  591. }
  592. m_value->visit(
  593. [&](TupleValue const& value) {
  594. serializer.serialize<TupleDescriptor>(*value.descriptor);
  595. serializer.serialize(static_cast<u32>(value.values.size()));
  596. for (auto const& element : value.values)
  597. serializer.serialize<Value>(element);
  598. },
  599. [&](auto const& value) { serializer.serialize(value); });
  600. }
  601. void Value::deserialize(Serializer& serializer)
  602. {
  603. auto type_flags = serializer.deserialize<u8>();
  604. auto type_data = static_cast<TypeData>(type_flags & 0xf0);
  605. m_type = static_cast<SQLType>(type_flags & 0x0f);
  606. if (type_data == TypeData::Null)
  607. return;
  608. switch (m_type) {
  609. case SQLType::Null:
  610. VERIFY_NOT_REACHED();
  611. break;
  612. case SQLType::Text:
  613. m_value = serializer.deserialize<DeprecatedString>();
  614. break;
  615. case SQLType::Integer:
  616. switch (type_data) {
  617. case TypeData::Int8:
  618. m_value = static_cast<i64>(serializer.deserialize<i8>(0));
  619. break;
  620. case TypeData::Int16:
  621. m_value = static_cast<i64>(serializer.deserialize<i16>(0));
  622. break;
  623. case TypeData::Int32:
  624. m_value = static_cast<i64>(serializer.deserialize<i32>(0));
  625. break;
  626. case TypeData::Int64:
  627. m_value = static_cast<i64>(serializer.deserialize<i64>(0));
  628. break;
  629. case TypeData::Uint8:
  630. m_value = static_cast<u64>(serializer.deserialize<u8>(0));
  631. break;
  632. case TypeData::Uint16:
  633. m_value = static_cast<u64>(serializer.deserialize<u16>(0));
  634. break;
  635. case TypeData::Uint32:
  636. m_value = static_cast<u64>(serializer.deserialize<u32>(0));
  637. break;
  638. case TypeData::Uint64:
  639. m_value = static_cast<u64>(serializer.deserialize<u64>(0));
  640. break;
  641. default:
  642. VERIFY_NOT_REACHED();
  643. break;
  644. }
  645. break;
  646. case SQLType::Float:
  647. m_value = serializer.deserialize<double>(0.0);
  648. break;
  649. case SQLType::Boolean:
  650. m_value = serializer.deserialize<bool>(false);
  651. break;
  652. case SQLType::Tuple: {
  653. auto descriptor = serializer.adopt_and_deserialize<TupleDescriptor>();
  654. auto size = serializer.deserialize<u32>();
  655. Vector<Value> values;
  656. values.ensure_capacity(size);
  657. for (size_t i = 0; i < size; ++i)
  658. values.unchecked_append(serializer.deserialize<Value>());
  659. m_value = TupleValue { move(descriptor), move(values) };
  660. break;
  661. }
  662. }
  663. }
  664. TupleElementDescriptor Value::descriptor() const
  665. {
  666. return { "", "", "", type(), Order::Ascending };
  667. }
  668. ResultOr<NonnullRefPtr<TupleDescriptor>> Value::infer_tuple_descriptor(Vector<Value> const& values)
  669. {
  670. auto descriptor = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) SQL::TupleDescriptor));
  671. TRY(descriptor->try_ensure_capacity(values.size()));
  672. for (auto const& element : values)
  673. descriptor->unchecked_append({ ""sv, ""sv, ""sv, element.type(), Order::Ascending });
  674. return descriptor;
  675. }
  676. }
  677. template<>
  678. ErrorOr<void> IPC::encode(Encoder& encoder, SQL::Value const& value)
  679. {
  680. auto type_flags = encode_type_flags(value);
  681. TRY(encoder.encode(type_flags));
  682. if (value.is_null())
  683. return {};
  684. switch (value.type()) {
  685. case SQL::SQLType::Null:
  686. return {};
  687. case SQL::SQLType::Text:
  688. return encoder.encode(value.to_deprecated_string());
  689. case SQL::SQLType::Integer:
  690. return SQL::downsize_integer(value, [&](auto integer, auto) {
  691. return encoder.encode(integer);
  692. });
  693. case SQL::SQLType::Float:
  694. return encoder.encode(value.to_double().value());
  695. case SQL::SQLType::Boolean:
  696. return encoder.encode(value.to_bool().value());
  697. case SQL::SQLType::Tuple:
  698. return encoder.encode(value.to_vector().value());
  699. }
  700. VERIFY_NOT_REACHED();
  701. }
  702. template<>
  703. ErrorOr<SQL::Value> IPC::decode(Decoder& decoder)
  704. {
  705. auto type_flags = TRY(decoder.decode<u8>());
  706. auto type_data = static_cast<SQL::TypeData>(type_flags & 0xf0);
  707. auto type = static_cast<SQL::SQLType>(type_flags & 0x0f);
  708. if (type_data == SQL::TypeData::Null)
  709. return SQL::Value { type };
  710. switch (type) {
  711. case SQL::SQLType::Null:
  712. return SQL::Value {};
  713. case SQL::SQLType::Text:
  714. return SQL::Value { TRY(decoder.decode<DeprecatedString>()) };
  715. case SQL::SQLType::Integer:
  716. switch (type_data) {
  717. case SQL::TypeData::Int8:
  718. return SQL::Value { TRY(decoder.decode<i8>()) };
  719. case SQL::TypeData::Int16:
  720. return SQL::Value { TRY(decoder.decode<i16>()) };
  721. case SQL::TypeData::Int32:
  722. return SQL::Value { TRY(decoder.decode<i32>()) };
  723. case SQL::TypeData::Int64:
  724. return SQL::Value { TRY(decoder.decode<i64>()) };
  725. case SQL::TypeData::Uint8:
  726. return SQL::Value { TRY(decoder.decode<u8>()) };
  727. case SQL::TypeData::Uint16:
  728. return SQL::Value { TRY(decoder.decode<u16>()) };
  729. case SQL::TypeData::Uint32:
  730. return SQL::Value { TRY(decoder.decode<u32>()) };
  731. case SQL::TypeData::Uint64:
  732. return SQL::Value { TRY(decoder.decode<u64>()) };
  733. default:
  734. break;
  735. }
  736. break;
  737. case SQL::SQLType::Float:
  738. return SQL::Value { TRY(decoder.decode<double>()) };
  739. case SQL::SQLType::Boolean:
  740. return SQL::Value { TRY(decoder.decode<bool>()) };
  741. case SQL::SQLType::Tuple: {
  742. auto tuple = TRY(decoder.decode<Vector<SQL::Value>>());
  743. auto value = SQL::Value::create_tuple(move(tuple));
  744. if (value.is_error())
  745. return Error::from_errno(to_underlying(value.error().error()));
  746. return value.release_value();
  747. }
  748. }
  749. VERIFY_NOT_REACHED();
  750. }