1#include "duckdb/parser/constraints/unique_constraint.hpp"
2
3#include "duckdb/common/field_writer.hpp"
4#include "duckdb/common/limits.hpp"
5#include "duckdb/parser/keyword_helper.hpp"
6
7namespace duckdb {
8
9UniqueConstraint::UniqueConstraint(LogicalIndex index, bool is_primary_key)
10 : Constraint(ConstraintType::UNIQUE), index(index), is_primary_key(is_primary_key) {
11}
12UniqueConstraint::UniqueConstraint(vector<string> columns, bool is_primary_key)
13 : Constraint(ConstraintType::UNIQUE), index(DConstants::INVALID_INDEX), columns(std::move(columns)),
14 is_primary_key(is_primary_key) {
15}
16
17string UniqueConstraint::ToString() const {
18 string base = is_primary_key ? "PRIMARY KEY(" : "UNIQUE(";
19 for (idx_t i = 0; i < columns.size(); i++) {
20 if (i > 0) {
21 base += ", ";
22 }
23 base += KeywordHelper::WriteOptionallyQuoted(text: columns[i]);
24 }
25 return base + ")";
26}
27
28unique_ptr<Constraint> UniqueConstraint::Copy() const {
29 if (index.index == DConstants::INVALID_INDEX) {
30 return make_uniq<UniqueConstraint>(args: columns, args: is_primary_key);
31 } else {
32 auto result = make_uniq<UniqueConstraint>(args: index, args: is_primary_key);
33 result->columns = columns;
34 return std::move(result);
35 }
36}
37
38void UniqueConstraint::Serialize(FieldWriter &writer) const {
39 writer.WriteField<bool>(element: is_primary_key);
40 writer.WriteField<uint64_t>(element: index.index);
41 D_ASSERT(columns.size() <= NumericLimits<uint32_t>::Maximum());
42 writer.WriteList<string>(elements: columns);
43}
44
45unique_ptr<Constraint> UniqueConstraint::Deserialize(FieldReader &source) {
46 auto is_primary_key = source.ReadRequired<bool>();
47 auto index = source.ReadRequired<uint64_t>();
48 auto columns = source.ReadRequiredList<string>();
49
50 if (index != DConstants::INVALID_INDEX) {
51 // single column parsed constraint
52 auto result = make_uniq<UniqueConstraint>(args: LogicalIndex(index), args&: is_primary_key);
53 result->columns = std::move(columns);
54 return std::move(result);
55 } else {
56 // column list parsed constraint
57 return make_uniq<UniqueConstraint>(args: std::move(columns), args&: is_primary_key);
58 }
59}
60
61} // namespace duckdb
62