TupleDescriptor.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /*
  2. * Copyright (c) 2021, Jan de Visser <jan@de-visser.net>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Vector.h>
  8. #include <LibSQL/Serializer.h>
  9. #include <LibSQL/Type.h>
  10. namespace SQL {
  11. struct TupleElementDescriptor {
  12. String name { "" };
  13. SQLType type { SQLType::Text };
  14. Order order { Order::Ascending };
  15. bool operator==(TupleElementDescriptor const&) const = default;
  16. void serialize(Serializer& serializer) const
  17. {
  18. serializer.serialize(name);
  19. serializer.serialize<u8>((u8)type);
  20. serializer.serialize<u8>((u8)order);
  21. }
  22. void deserialize(Serializer& serializer)
  23. {
  24. name = serializer.deserialize<String>();
  25. type = (SQLType)serializer.deserialize<u8>();
  26. order = (Order)serializer.deserialize<u8>();
  27. }
  28. size_t length() const
  29. {
  30. return (sizeof(u32) + name.length()) + 2 * sizeof(u8);
  31. }
  32. String to_string() const
  33. {
  34. return String::formatted(" name: {} type: {} order: {}", name, SQLType_name(type), Order_name(order));
  35. }
  36. };
  37. class TupleDescriptor
  38. : public Vector<TupleElementDescriptor>
  39. , public RefCounted<TupleDescriptor> {
  40. public:
  41. TupleDescriptor() = default;
  42. ~TupleDescriptor() = default;
  43. [[nodiscard]] int compare_ignoring_names(TupleDescriptor const& other) const
  44. {
  45. if (size() != other.size())
  46. return (int)size() - (int)other.size();
  47. for (auto ix = 0u; ix < size(); ++ix) {
  48. auto elem = (*this)[ix];
  49. auto other_elem = other[ix];
  50. if ((elem.type != other_elem.type) || (elem.order != other_elem.order)) {
  51. return 1;
  52. }
  53. }
  54. return 0;
  55. }
  56. void serialize(Serializer& serializer) const
  57. {
  58. serializer.serialize<u32>(size());
  59. for (auto& element : *this) {
  60. serializer.serialize<TupleElementDescriptor>(element);
  61. }
  62. }
  63. void deserialize(Serializer& serializer)
  64. {
  65. auto sz = serializer.deserialize<u32>();
  66. for (auto ix = 0u; ix < sz; ix++) {
  67. append(serializer.deserialize<TupleElementDescriptor>());
  68. }
  69. }
  70. size_t length() const
  71. {
  72. size_t len = sizeof(u32);
  73. for (auto& element : *this) {
  74. len += element.length();
  75. }
  76. return len;
  77. }
  78. String to_string() const
  79. {
  80. Vector<String> elements;
  81. for (auto& element : *this) {
  82. elements.append(element.to_string());
  83. }
  84. return String::formatted("[\n{}\n]", String::join("\n", elements));
  85. }
  86. using Vector<TupleElementDescriptor>::operator==;
  87. };
  88. }