I am having 2 tables with PK and FK reference as below.
CREATE TABLE IF NOT EXISTS User
(
userid VARCHAR(255) PRIMARY KEY
);
CREATE TABLE IF NOT EXISTS UserType
(
email VARCHAR(255) PRIMARY KEY,
userId VARCHAR(255),
type VARCHAR(255),
FOREIGN KEY (userId) REFERENCES User (userId)
);
Table: User
UserId (PK) |
---|
1 |
2 |
Table: UserType
Email (PK) | UserId (FK) | Type |
---|---|---|
[email protected] | 1 | xxx |
[email protected] | 2 | yyy |
I am generating userid from code and inserting using sqlx – sqlite as below
async fn create_user(
&self,
user: &User,
) -> Result<(), CreateError> {
let query = "insert into User (id) values (?1)";
let query_local = "insert or ignore into UserType (email,user_id) values (?1,?2)";
let mut conn = self
.pool
.acquire()
.map_err("xxx")
.await?;
let mut tx = conn.begin().map_err("xxx").await?;
sqlx::query(query)
.bind(user.userid.as_str())
.execute(&mut *tx)
.map_err("xxx")
.await?;
sqlx::query(query_local)
.bind(user.email.as_str())
.bind(user.userid.as_str())
.execute(&mut *tx)
.map_err("xxx")
.await?;
tx.commit().map_err("xxx").await?;
Ok(())
}
Now in case of getting duplicate email, on conflict while inserting ‘UserType’ (second) table, How can i avoid the UserId inserted in ‘User’ (first) table? I am new to relational DB and SQL. Is there idiomatic way to do this through query or through transaction? Please help
Note: I know this design is vague but its required for processing further for application reasons