Skip to content
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

feat: Add support for serde behind feature flag #65

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,13 @@ edition = "2021"

[dependencies]
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }
serde_json = { version = "1.0.128", optional = true }
serde = { version = "1.0.210", optional = true }

[dev-dependencies]
json = "0.12"
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0.210", features = ["derive"] }

[features]
serde = ["dep:serde_json", "dep:serde"]
143 changes: 132 additions & 11 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -419,14 +419,44 @@ impl Builder {
/// .insert(r#"[{ "username": "soedirgo", "status": "online" },
/// { "username": "jose", "status": "offline" }]"#);
/// ```
pub fn insert<T>(mut self, body: T) -> Self
#[cfg(not(feature = "serde"))]
pub fn insert<T>(self, body: T) -> Self
where
T: Into<String>,
{
self.insert_impl(body.into())
}

/// Performs an INSERT of the `body` (in JSON) into the table.
///
/// # Example
///
/// ```
/// use postgrest::Postgrest;
///
/// #[derive(serde::Serialize)]
/// struct MyStruct {}
///
/// let my_serializable_struct = MyStruct {};
///
/// let client = Postgrest::new("https://your.postgrest.endpoint");
/// client
/// .from("users")
/// .insert(&my_serializable_struct).unwrap();
/// ```
#[cfg(feature = "serde")]
pub fn insert<T>(self, body: &T) -> serde_json::Result<Self>
where
T: serde::Serialize,
{
Ok(self.insert_impl(serde_json::to_string(body)?))
}

fn insert_impl(mut self, body: String) -> Self {
self.method = Method::POST;
self.headers
.insert("Prefer", HeaderValue::from_static("return=representation"));
self.body = Some(body.into());
self.body = Some(body);
self
}

Expand All @@ -448,16 +478,51 @@ impl Builder {
/// .upsert(r#"[{ "username": "soedirgo", "status": "online" },
/// { "username": "jose", "status": "offline" }]"#);
/// ```
pub fn upsert<T>(mut self, body: T) -> Self
#[cfg(not(feature = "serde"))]
pub fn upsert<T>(self, body: T) -> Self
where
T: Into<String>,
{
self.upsert_impl(body.into())
}

/// Performs an upsert of the `body` (in JSON) into the table.
///
/// # Note
///
/// This merges duplicates by default. Ignoring duplicates is possible via
/// PostgREST, but is currently unsupported.
///
/// # Example
///
/// ```
/// use postgrest::Postgrest;
///
/// #[derive(serde::Serialize)]
/// struct MyStruct {}
///
/// let my_serializable_struct = MyStruct {};
///
/// let client = Postgrest::new("https://your.postgrest.endpoint");
/// client
/// .from("users")
/// .upsert(&my_serializable_struct).unwrap();
/// ```
#[cfg(feature = "serde")]
pub fn upsert<T>(self, body: &T) -> serde_json::Result<Self>
where
T: serde::Serialize,
{
Ok(self.upsert_impl(serde_json::to_string(body)?))
}

fn upsert_impl(mut self, body: String) -> Self {
self.method = Method::POST;
self.headers.insert(
"Prefer",
HeaderValue::from_static("return=representation,resolution=merge-duplicates"),
);
self.body = Some(body.into());
self.body = Some(body);
self
}

Expand All @@ -478,11 +543,23 @@ impl Builder {
/// let client = Postgrest::new("https://your.postgrest.endpoint");
/// // Suppose `users` are keyed an SERIAL primary key,
/// // but have a unique index on `username`.
/// client
/// .from("users")
/// .upsert(r#"[{ "username": "soedirgo", "status": "online" },
/// { "username": "jose", "status": "offline" }]"#)
/// .on_conflict("username");
#[cfg_attr(not(feature = "serde"), doc = r##"
client
.from("users")
.upsert(r#"[{ "username": "soedirgo", "status": "online" },
{ "username": "jose", "status": "offline" }]"#)
.on_conflict("username");
"##)]
#[cfg_attr(feature = "serde", doc = r##"
#[derive(serde::Serialize)]
struct MyStruct {}

let my_serializable_struct = MyStruct {};

client
.from("users")
.upsert(&my_serializable_struct).unwrap();
"##)]
/// ```
pub fn on_conflict<T>(mut self, columns: T) -> Self
where
Expand All @@ -506,14 +583,44 @@ impl Builder {
/// .eq("username", "soedirgo")
/// .update(r#"{ "status": "offline" }"#);
/// ```
pub fn update<T>(mut self, body: T) -> Self
#[cfg(not(feature = "serde"))]
pub fn update<T>(self, body: T) -> Self
where
T: Into<String>,
{
self.update_impl(body.into())
}

/// Performs an UPDATE using the `body` (in JSON) on the table.
///
/// # Example
///
/// ```
/// use postgrest::Postgrest;
///
/// #[derive(serde::Serialize)]
/// struct MyStruct {}
///
/// let my_serializable_struct = MyStruct {};
///
/// let client = Postgrest::new("https://your.postgrest.endpoint");
/// client
/// .from("users")
/// .eq("username", "soedirgo")
/// .update(&my_serializable_struct).unwrap();
/// ```
#[cfg(feature = "serde")]
pub fn update<T>(self, body: &T) -> serde_json::Result<Self>
where
T: serde::Serialize {
Ok(self.update_impl(serde_json::to_string(body)?))
}

fn update_impl(mut self, body: String) -> Self {
self.method = Method::PATCH;
self.headers
.insert("Prefer", HeaderValue::from_static("return=representation"));
self.body = Some(body.into());
self.body = Some(body);
self
}

Expand Down Expand Up @@ -692,6 +799,7 @@ mod tests {
}

#[test]
#[cfg(not(feature = "serde"))]
fn upsert_assert_prefer_header() {
let client = Client::new();
let builder = Builder::new(TABLE_URL, None, HeaderMap::new(), client).upsert("ignored");
Expand All @@ -700,6 +808,19 @@ mod tests {
HeaderValue::from_static("return=representation,resolution=merge-duplicates")
);
}

#[test]
#[cfg(feature = "serde")]
fn upsert_assert_prefer_header_serde() {
let client = Client::new();
let builder = Builder::new(TABLE_URL, None, HeaderMap::new(), client)
.upsert(&())
.unwrap();
assert_eq!(
builder.headers.get("Prefer").unwrap(),
HeaderValue::from_static("return=representation,resolution=merge-duplicates")
);
}

#[test]
fn not_rpc_should_not_have_flag() {
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
//! Updating a table:
//! ```
//! # use postgrest::Postgrest;
//! # #[cfg(not(feature = "serde"))]
//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
//! # let client = Postgrest::new("https://your.postgrest.endpoint");
//! let resp = client
Expand Down
Loading
Loading