Value.cpp 27 KB

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