1//===----------------------------------------------------------------------===//
2// DuckDB
3//
4// duckdb/parser/constraint.hpp
5//
6//
7//===----------------------------------------------------------------------===//
8
9#pragma once
10
11#include "duckdb/common/common.hpp"
12#include "duckdb/common/vector.hpp"
13#include "duckdb/common/exception.hpp"
14
15namespace duckdb {
16
17class Serializer;
18class Deserializer;
19class FieldWriter;
20class FieldReader;
21
22//===--------------------------------------------------------------------===//
23// Constraint Types
24//===--------------------------------------------------------------------===//
25enum class ConstraintType : uint8_t {
26 INVALID = 0, // invalid constraint type
27 NOT_NULL = 1, // NOT NULL constraint
28 CHECK = 2, // CHECK constraint
29 UNIQUE = 3, // UNIQUE constraint
30 FOREIGN_KEY = 4, // FOREIGN KEY constraint
31};
32
33enum class ForeignKeyType : uint8_t {
34 FK_TYPE_PRIMARY_KEY_TABLE = 0, // main table
35 FK_TYPE_FOREIGN_KEY_TABLE = 1, // referencing table
36 FK_TYPE_SELF_REFERENCE_TABLE = 2 // self refrencing table
37};
38
39struct ForeignKeyInfo {
40 ForeignKeyType type;
41 string schema;
42 //! if type is FK_TYPE_FOREIGN_KEY_TABLE, means main key table, if type is FK_TYPE_PRIMARY_KEY_TABLE, means foreign
43 //! key table
44 string table;
45 //! The set of main key table's column's index
46 vector<PhysicalIndex> pk_keys;
47 //! The set of foreign key table's column's index
48 vector<PhysicalIndex> fk_keys;
49};
50
51//! Constraint is the base class of any type of table constraint.
52class Constraint {
53public:
54 DUCKDB_API explicit Constraint(ConstraintType type);
55 DUCKDB_API virtual ~Constraint();
56
57 ConstraintType type;
58
59public:
60 DUCKDB_API virtual string ToString() const = 0;
61 DUCKDB_API void Print() const;
62
63 DUCKDB_API virtual unique_ptr<Constraint> Copy() const = 0;
64 //! Serializes a Constraint to a stand-alone binary blob
65 DUCKDB_API void Serialize(Serializer &serializer) const;
66 //! Serializes a Constraint to a stand-alone binary blob
67 DUCKDB_API virtual void Serialize(FieldWriter &writer) const = 0;
68 //! Deserializes a blob back into a Constraint
69 DUCKDB_API static unique_ptr<Constraint> Deserialize(Deserializer &source);
70
71public:
72 template <class TARGET>
73 TARGET &Cast() {
74 if (type != TARGET::TYPE) {
75 throw InternalException("Failed to cast constraint to type - constraint type mismatch");
76 }
77 return reinterpret_cast<TARGET &>(*this);
78 }
79
80 template <class TARGET>
81 const TARGET &Cast() const {
82 if (type != TARGET::TYPE) {
83 throw InternalException("Failed to cast constraint to type - constraint type mismatch");
84 }
85 return reinterpret_cast<const TARGET &>(*this);
86 }
87};
88} // namespace duckdb
89