[odb-users] polymorphic inheritance, typeid, odb::object_not_persistent

MM finjulhich at gmail.com
Mon Jul 20 14:32:50 EDT 2015


Hello,

I have the following:

namespace NS
{
class Base {
public:
  const std::string& name() const;
  void name(const std::string&);
  virtual ~exchange() =default;
protected:
  exchange() = default;
  exchange(const std::string&, const sometype&);

private:
  std::string name_;
  const sometype* cal_;
};

class D1 : public Base {
public:
  D1() = default;
  D1(const std::string&,const sometype&);
private:
   /// some virtual function overrides
};
class D2 : public Base {
/// same
};
...
class D10 : public Base {
/// same
};
}

The SQL that was just generated by the odb compiler is:

CREATE TABLE "Base" (
  "name" TEXT NULL PRIMARY KEY,
  "typeid" TEXT NULL,
  "cal" TEXT NULL,
  CONSTRAINT "cal_fk"
    FOREIGN KEY ("cal")
    REFERENCES "OtherTable" ("name")
    DEFERRABLE INITIALLY DEFERRED);

CREATE TABLE "D1" (
  "name" TEXT NULL PRIMARY KEY,
  CONSTRAINT "name_fk"
    FOREIGN KEY ("name")
    REFERENCES "Base" ("name")
    ON DELETE CASCADE);

/// and so on for all the D2... D10

In the database, table Base looks like:

name      typeid         cal
D1            NS::D1       NULL
D2            NS::D2       cal2
...
D10          NS::D10     NULL

and there is 1 table for each of the derived classes, each with 1 row and 1
column:

table D1:
name
D1

table D2:
name
D2

... and so on.

When running this loading code

odb::sqlite::database db{settings.db_filename, SQLITE_OPEN_READONLY};
odb::session s;
odb::transaction t{ db.begin() };

{
      auto res = db.query<NS::Base>();
      std::size_t cnt = 0u;
      for (auto i=std::begin(res); i!=std::end(res); ++i, ++cnt)
        some_function( i.load() );
      std::cout<<" "<<cnt<<" items loaded" << std::endl;
}

I get this exception: odb::object_not_persistent

The intent is to load from the database all the persistent objects  (the
derived) from the Base table, and assign them a concrete derived instance
(D1...D10) according to the typeid, and populate the name field

I don't know if this is expected to work, and what is the correction if
something is wrong.

Regards,

MM


More information about the odb-users mailing list