Skip to content

Commit

Permalink
Database queries with Diesel (#192)
Browse files Browse the repository at this point in the history
  • Loading branch information
david-crespo authored Sep 1, 2021
1 parent 40f1d2f commit ee3fa44
Show file tree
Hide file tree
Showing 30 changed files with 2,309 additions and 3,311 deletions.
94 changes: 81 additions & 13 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions diesel.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# For documentation on how to configure this file,
# see diesel.rs/guides/configuring-diesel-cli

[print_schema]
file = "omicron-nexus/src/db/diesel_schema.rs"
2 changes: 2 additions & 0 deletions omicron-common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ edition = "2018"
[dependencies]
anyhow = "1.0"
async-trait = "0.1.51"
# Tracking pending 2.0 version.
diesel = { git = "https://github.com/diesel-rs/diesel", rev = "a39dd2e", features = ["postgres", "r2d2", "chrono", "uuid"] }
futures = "0.3.15"
http = "0.2.0"
hyper = "0.14"
Expand Down
42 changes: 42 additions & 0 deletions omicron-common/src/api/external/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

use crate::api::external::Name;
use crate::api::external::ResourceType;
use diesel::result::DatabaseErrorKind as DieselErrorKind;
use diesel::result::Error as DieselError;
use dropshot::HttpError;
use dropshot::HttpErrorResponseBody;
use serde::Deserialize;
Expand Down Expand Up @@ -161,6 +163,46 @@ impl Error {
},
}
}

/// Converts a Diesel error to an external type error.
pub fn from_diesel(
error: DieselError,
resource_type: ResourceType,
lookup_type: LookupType,
) -> Error {
match error {
DieselError::NotFound => {
Error::ObjectNotFound { type_name: resource_type, lookup_type }
}
DieselError::DatabaseError(kind, _info) => {
Error::unavail(format!("Database error: {:?}", kind).as_str())
}
_ => Error::internal_error("Unknown diesel error"),
}
}

/// Converts a Diesel error to an external type error, when requested as
/// part of a creation operation.
pub fn from_diesel_create(
error: DieselError,
resource_type: ResourceType,
object_name: &str,
) -> Error {
match error {
DieselError::DatabaseError(kind, _info) => match kind {
DieselErrorKind::UniqueViolation => {
Error::ObjectAlreadyExists {
type_name: resource_type,
object_name: object_name.to_string(),
}
}
_ => Error::unavail(
format!("Database error: {:?}", kind).as_str(),
),
},
_ => Error::internal_error("Unknown diesel error"),
}
}
}

impl From<Error> for HttpError {
Expand Down
Loading

0 comments on commit ee3fa44

Please sign in to comment.