sorosh_sabz
sorosh_sabz

Reputation: 3003

How to insert an entry in SQLite ORM with a composite key

I using the SQLite ORM library for using SQLite in my program and I have table like below:

auto storage = make_storage("test_remove.sqlite",
                            make_table("objects",
                                       make_column("key_part_1",
                                                   &Object::key_part_1),
                                       make_column("key_part_2",
                                                   &Object::key_part_2),
                                       make_column("name",
                                                   &Object::name),
                                       primary_key(&Object::key_part_1, &Object::key_part_2)));

That, as you can see, this table have a composite key (key_part_1 and key_part_2). When I create an instance from Object like below,

Object object{0, 0, "dummy"};

and try to insert in a table

auto id1 = storage.insert(object);

I get an exception.

How can I insert an object to this table?

Upvotes: 4

Views: 624

Answers (1)

sorosh_sabz
sorosh_sabz

Reputation: 3003

As you can see in one issue in GitHub for SQLite ORM, projects with a Composite key title the method, for inserting an object with a composite key you must use the replace function instead of the insert function like below.

Consider you have an entity like below:

struct Object
{
    int key_part_1;
    int key_part_2;
    std::string name;
};

And create a schema like below:


auto storage = make_storage("test_remove.sqlite",
                            make_table("objects",
                                  make_column("key_part_1",
                                               &Object::key_part_1),
                                  make_column("key_part_2",
                                               &Object::key_part_2),
                                  make_column("name",
                                               &Object::name),
                                  primary_key(&Object::key_part_1, &Object::key_part_2)));

So you can insert one instance of this entity like below:

Object object{0, 0, "Skillet"};

storage.replace(object);

Upvotes: 1

Related Questions