Value.cpp 27 KB

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