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