Let’s suppose I have a list of derived objects from some base:
class Circle : public Shape;
class Rectangle : public Shape;
There is object, which has vector of Shape *
as member variable:
class Screen {
std::vector<Shape *> shapes_;
}
But now I need to persist this in database (PostgreSQL to be precise). Only way I thought of is to have table per class, something like this:
table screen ();
table circle (
int screen_id;
);
table rectangle (
int screen_id;
);
And after retrieving from object of type Screen do query for Circles and Rectangles with screen.id. Should be doable.
However I fear that when number of types grows (and it will), it would mean many db queries for just one object retrieval/persist.
Right know we’ll have about 10 types I think? That’s 11 db queries just to retrieve one Screen object.
So my questing is, is there better way to achieve my goal? I’m fine with redesigning my code if needed, I just would like some O(1) solution in correlation to number of types (my solution is O(n) ).
Thank you guys ^_^
NOTE: based on comment I’m adding that tables of Circles and Rectangles etc. will be used only to put together Screen object. I don’t access (look-up, retrieve, persist, …) to them individually, only as parts of Screen(s). They don’t even have to be in their own table. Just didn’t find a way to nicely put it all together :/
4
All you need is one table, with a simple design. You need
- A field for the uid
- Possibly a field for a timestamp (you may need that, you may not, don’t know your particular circumstances).
- A field in which you serialize the Screen object and all the Shapes it contains.
That means just one write to save and one read to recover the Screen and its shapes. Why do more, given how simple your requirements are?
I recommend you serialize to a json format. Postgresql now has a JSON data type and JSON operators and functions. So you can validate and examine the serialized data in the db if you want to, without having to extract and normalize it.
Other benefits of this approach:
- If you later decide to serialize somewhere else (into a file or memory cache, for example), it would require minimal change to the code.
- No need to change your db schema if you add new types of Shapes or change the structure of any existing objects.
6