Dvex
Dvex

Reputation: 971

Is it possible to use a table without primary key in diesel? Rust

I am new to Rust and I am making an API using Diesel and Actix-web. I have a DB in pgsql and mongodb and I use diesel 1.4.4 only for pgsql.

First, I did a test creating a DB with its tables and its primary keys and everything works fine. But, there are always scenarios in which there will be tables that do not have a primary key and only have foreign keys.

I have noticed that Diesel only supports table with Primary Keys, but if you wanted to use a table that does not have a primary key and only has a foreign key, is there a way to import that table? Manually can you? That is, defining it in the schema.rs and in my models.rs.

Upvotes: 3

Views: 1953

Answers (1)

weiznich
weiznich

Reputation: 3455

Tables without primary key are not supported by diesel, because they are bad practice from a database point of view. In almost all cases there is some combination of columns that form a natural primary key, otherwise adding a artificial one is preferred. If you have a table that consists only of foreign key columns the natural foreign key would be constructed out of all those columns.

That said: It is possible to use diesel with tables without primary key column by just telling diesel that a specific (combination) of columns should be treated as primary key. In this case you need to write your table! definition for those tables manually.

Upvotes: 2

Related Questions