Value.cpp 27 KB

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