Skip to content

Commit ee3fa44

Browse files
authored
Database queries with Diesel (#192)
1 parent 40f1d2f commit ee3fa44

30 files changed

+2309
-3311
lines changed

Cargo.lock

+81-13
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

diesel.toml

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# For documentation on how to configure this file,
2+
# see diesel.rs/guides/configuring-diesel-cli
3+
4+
[print_schema]
5+
file = "omicron-nexus/src/db/diesel_schema.rs"

omicron-common/Cargo.toml

+2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ edition = "2018"
66
[dependencies]
77
anyhow = "1.0"
88
async-trait = "0.1.51"
9+
# Tracking pending 2.0 version.
10+
diesel = { git = "https://github.com/diesel-rs/diesel", rev = "a39dd2e", features = ["postgres", "r2d2", "chrono", "uuid"] }
911
futures = "0.3.15"
1012
http = "0.2.0"
1113
hyper = "0.14"

omicron-common/src/api/external/error.rs

+42
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66

77
use crate::api::external::Name;
88
use crate::api::external::ResourceType;
9+
use diesel::result::DatabaseErrorKind as DieselErrorKind;
10+
use diesel::result::Error as DieselError;
911
use dropshot::HttpError;
1012
use dropshot::HttpErrorResponseBody;
1113
use serde::Deserialize;
@@ -161,6 +163,46 @@ impl Error {
161163
},
162164
}
163165
}
166+
167+
/// Converts a Diesel error to an external type error.
168+
pub fn from_diesel(
169+
error: DieselError,
170+
resource_type: ResourceType,
171+
lookup_type: LookupType,
172+
) -> Error {
173+
match error {
174+
DieselError::NotFound => {
175+
Error::ObjectNotFound { type_name: resource_type, lookup_type }
176+
}
177+
DieselError::DatabaseError(kind, _info) => {
178+
Error::unavail(format!("Database error: {:?}", kind).as_str())
179+
}
180+
_ => Error::internal_error("Unknown diesel error"),
181+
}
182+
}
183+
184+
/// Converts a Diesel error to an external type error, when requested as
185+
/// part of a creation operation.
186+
pub fn from_diesel_create(
187+
error: DieselError,
188+
resource_type: ResourceType,
189+
object_name: &str,
190+
) -> Error {
191+
match error {
192+
DieselError::DatabaseError(kind, _info) => match kind {
193+
DieselErrorKind::UniqueViolation => {
194+
Error::ObjectAlreadyExists {
195+
type_name: resource_type,
196+
object_name: object_name.to_string(),
197+
}
198+
}
199+
_ => Error::unavail(
200+
format!("Database error: {:?}", kind).as_str(),
201+
),
202+
},
203+
_ => Error::internal_error("Unknown diesel error"),
204+
}
205+
}
164206
}
165207

166208
impl From<Error> for HttpError {

0 commit comments

Comments
 (0)