Project

General

Profile

Wt::Dbo composite natural primary key issues » example.cpp

Dawid Oriański, 04/17/2017 10:23 PM

 
#include <string>

#include <Wt/Dbo/Dbo>
#include <Wt/Dbo/SqlTraits>
#include <Wt/Dbo/WtSqlTraits>

class BelongingName;
class Child;
class Root;

typedef Wt::Dbo::ptr<Child> ChildPtr;
typedef Wt::Dbo::ptr<Root> RootPtr;

typedef Wt::Dbo::collection<ChildPtr> ChildCollection;
typedef Wt::Dbo::collection<RootPtr> RootCollection;


namespace Wt{
namespace Dbo{

template<>
struct dbo_traits<Root> : public dbo_default_traits
{
typedef WString IdType;

static IdType invalidId()
{
return IdType();
};

static const char* surrogateIdField()
{
return 0;
};
};
} // namespace Dbo
} // namespace Wt



class BelongingName
{
public:
BelongingName()
: name()
, parent()
{};

BelongingName(const Wt::Dbo::ptr<Root>& parent, const Wt::WString& name)
: name(name)
, parent(parent)
{};


// Accessors
const Wt::WString& getName() const
{
return name;
};

const Wt::Dbo::ptr<Root>& getRoot() const
{
return parent;
};


// Comparison operators
bool operator==(const BelongingName& other) const
{
return parent == other.parent && name == other.name;
};

bool operator<(const BelongingName& other) const;

private:
Wt::WString name;
Wt::Dbo::ptr<Root> parent;
};

namespace Wt{
namespace Dbo{

template<>
struct dbo_traits<Child> : public dbo_default_traits
{
typedef BelongingName IdType;

static IdType invalidId()
{
return IdType();
};

static const char* surrogateIdField()
{
return 0;
};
};

} // namespace Dbo
} // namespace Wt


class Child
{
public:
Child()
{};

Child(BelongingName id)
: id(id)
{};

const BelongingName& getId() const
{
return id;
};

template<class Action>
void persist(Action& a)
{
Wt::Dbo::id(a, id, "root_child");
};

private:
BelongingName id;
};


class Root
{
public:
Root()
{};

Root(Wt::WString name)
: name(name)
{};

const Wt::WString& getName() const
{
return name;
};

template<class Action>
void persist(Action& a)
{
Wt::Dbo::field(a, name, "name");
Wt::Dbo::hasMany(a, rights, Wt::Dbo::ManyToOne, "root_child");
};

private:
Wt::WString name;
ChildCollection rights;
};

bool BelongingName::operator<(const BelongingName& other) const
{
if( parent->getName() == other.parent->getName() )
return name < other.name;
else if( parent->getName() < other.parent->getName() )
return true;

return false;
};



namespace Wt{
namespace Dbo{

template<class Action>
void field(Action& action, BelongingName& prop, const Wt::WString& name, int size = -1)
{
belongsTo(action, prop.getRoot(), name, NotNull | OnUpdateCascade | OnDeleteCascade);
field(action, prop.getName(), name + "_name");
}

} // namespace Dbo
} // namespace Wt

namespace std{

ostream& operator<< (ostream& o, const BelongingName& bn)
{
return o << bn.getName() << '@' << bn.getRoot()->getName();
}
} // namespace std

DBO_INSTANTIATE_TEMPLATES(Child);
DBO_INSTANTIATE_TEMPLATES(Root);

    (1-1/1)