New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: help with foreign key #405

Closed
vitiral opened this Issue Aug 15, 2016 · 4 comments

Comments

Projects
None yet
2 participants
@vitiral

vitiral commented Aug 15, 2016

I am fairly new to SQL and rust, and am trying to make a simple test-tracking tool with a db backend (written in diesel and rust).

For an ultra simple version, my tables look like:

CREATE TABLE tests {
  name TEXT PRIMARY KEY,
}

CREATE TABLE runs {
  id SERIAL PRIMARY KEY,
  test_name TEXT references tests(name),
  passed bool NOT NULL,
}

I can't find any documentation on how to deal with foreign keys in diesel. Can I just make a struct like:

#[derive(Queryable)]
struct Run {
  id: i32,
  test_name: String,
  passed: bool,
}

#[insertable_into(runs)]
struct NewRun {
  test_name: String,
  passed: bool,
}

and diesel will handle creating a new row in test_names when the name doesn't exist? What is the best way to handle this?

@sgrif

This comment has been minimized.

Member

sgrif commented Aug 15, 2016

diesel::insert(&NewRun { ... }).into(runs::table).execute(&connection) will insert a new run. The fact that there is a foreign key will not have any impact on the flow (other than providing potential error conditions). Your test_name column should probably be NOT NULL or your field should be Option<String> though.

@sgrif sgrif closed this Aug 15, 2016

@vitiral

This comment has been minimized.

vitiral commented Aug 15, 2016

Thanks a ton! Would be great if this could be incorporated into the documentation -- the fact that this is handled automagically makes diesel even more appealing :)

I imagine if I wanted to pointed to a name_id foreign key instead then this would be a two step process? (first create the Name and/or query the name_id, then create the Run?)

@sgrif

This comment has been minimized.

Member

sgrif commented Aug 15, 2016

the fact that this is handled automagically makes diesel even more appealing

Not sure what you mean? We're literally not handling anything here. And yes your question about the process is correct.

@vitiral

This comment has been minimized.

vitiral commented Aug 17, 2016

the fact that you are adding a row to both the tests table and the runs table at once is pretty cool IMO.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment