-
Notifications
You must be signed in to change notification settings - Fork 5
/
insert.rs
324 lines (301 loc) · 12.1 KB
/
insert.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
//! ## Insert Operations
//!
//! This module provides functionalities to insert new rows into a Supabase table.
//! It leverages the Supabase REST API for performing these operations.
//!
//! ## Features
//!
//! - **Insert**: Add new rows to a table.
//! - **Insert if Unique**: Add a new row only if it does not violate a UNIQUE constraint.
//!
//! ## Usage
//!
//! Before using these operations, ensure you have a valid `SupabaseClient` instance.
//! You can then use the `insert` or `insert_if_unique` methods provided by the client to perform the desired operation.
//!
//! ### Insert Example
//!
//! ```
//! # use serde_json::json;
//! # use supabase_rs::SupabaseClient;
//! #[tokio::main]
//! async fn main() {
//! let client = SupabaseClient::new(
//! "your_supabase_url".to_string(), "your_supabase_key".to_string()
//! ).unwrap();
//! let insert_result = client.insert(
//! "your_table_name", json!({"column_name": "value"})
//! ).await;
//! }
//! ```
//!
//! ### Insert if Unique Example
//!
//! ```
//! # use serde_json::json;
//! # use supabase_rs::SupabaseClient;
//! #[tokio::main]
//! async fn main() {
//! let client = SupabaseClient::new(
//! "your_supabase_url".to_string(), "your_supabase_key".to_string()
//! ).unwrap();
//! let unique_insert_result = client.insert_if_unique(
//! "your_table_name", json!({"unique_column_name": "unique_value"})
//! ).await;
//! }
//! ```
//!
//! ## Error Handling
//!
//! Both `insert` and `insert_if_unique` methods return a `Result<String, String>`, where `Ok(String)` contains the ID of the inserted row,
//! and `Err(String)` contains an error message in case of failure.
use crate::{generate_random_id, SupabaseClient};
use reqwest::Response;
use serde_json::{json, Value};
impl SupabaseClient {
/// Inserts a new row into the specified table with automatically generated ID for column `id`.
///
/// # Arguments
/// * `table_name` - A string slice that holds the name of the table.
/// * `body` - A JSON value containing the data to be inserted.
///
/// # Example
/// ```ignore
/// // Initialize the Supabase client
/// use supabase_rs::SupabaseClient;
/// let client = SupabaseClient::new("your_supabase_url", "your_supabase_key");
///
/// // This will insert a new row into the table
/// let insert_result = client.insert(
/// "your_table_name",
/// json!(
/// {"column_name": "value"}
/// )
/// ).await;
/// ```
///
///
/// # Returns
/// This method returns a `Result<String, String>`. On success, it returns `Ok(String)` with the new row's ID,
/// and on failure, it returns `Err(String)` with an error message.
pub async fn insert(&self, table_name: &str, mut body: Value) -> Result<String, String> {
let endpoint: String = format!("{}/rest/v1/{}", self.url, table_name);
#[cfg(feature = "nightly")]
use crate::nightly::print_nightly_warning;
#[cfg(feature = "nightly")]
print_nightly_warning();
let new_id: i64 = generate_random_id();
body["id"] = json!(new_id);
let response: Response = match self
.client
.post(&endpoint)
.header("apikey", &self.api_key)
.header("Authorization", format!("Bearer {}", &self.api_key))
.header("Content-Type", "application/json")
.header("x_client_info", "supabase-rs/0.3.7")
.body(body.to_string())
.send()
.await
{
Ok(response) => response,
Err(e) => return Err(e.to_string()),
};
if response.status().is_success() {
Ok(new_id.to_string())
} else if response.status().as_u16() == 409 {
println!("\x1b[31mError 409: Duplicate entry. The value you're trying to insert may already exist in a column with a UNIQUE constraint.\x1b[0m");
return Err("\x1b[31mError 409: Duplicate entry. The value you're trying to insert may already exist in a column with a UNIQUE constraint.\x1b[0m".to_string());
} else {
println!("\x1b[31mError: {:?}\x1b[0m", response);
return Err(response.status().to_string());
}
}
/// Inserts a new row into the specified table with a user-defined ID or Supabase backend generated ID.
///
/// # Arguments
/// * `table_name` - A string slice that holds the name of the table.
/// * `body` - A JSON value containing the data to be inserted.
///
/// # Example
/// ```ignore
/// // Initialize the Supabase client
/// let client = SupabaseClient::new("your_supabase_url", "your_supabase_key");
///
/// // This will insert a new row into the table
/// let insert_result = client.insert(
/// "your_table_name",
/// json!(
/// {
/// "id": "your_id", // Optional
/// "column_name": "value"
/// }
/// )
/// ).await;
/// ```
///
/// # Returns
/// This method returns a `Result<(), String>`. On success, it returns `Ok(())`,
/// and on failure, it returns `Err(String)` with an error message.
pub async fn insert_without_defined_key(
&self,
table_name: &str,
body: Value,
) -> Result<(), String> {
let endpoint: String = format!("{}/rest/v1/{}", self.url, table_name);
#[cfg(feature = "nightly")]
use crate::nightly::print_nightly_warning;
#[cfg(feature = "nightly")]
print_nightly_warning();
let response: Response = match self
.client
.post(&endpoint)
.header("apikey", &self.api_key)
.header("Authorization", format!("Bearer {}", &self.api_key))
.header("Content-Type", "application/json")
.header("x_client_info", "supabase-rs/0.3.7")
.body(body.to_string())
.send()
.await
{
Ok(response) => response,
Err(e) => return Err(e.to_string()),
};
if response.status().is_success() {
Ok(())
} else if response.status().as_u16() == 409 {
println!("\x1b[31mError 409: Duplicate entry. The value you're trying to insert may already exist in a column with a UNIQUE constraint.\x1b[0m");
return Err("\x1b[31mError 409: Duplicate entry. The value you're trying to insert may already exist in a column with a UNIQUE constraint.\x1b[0m".to_string());
} else {
println!("\x1b[31mError: {:?}\x1b[0m", response);
return Err(response.status().to_string());
}
}
/// Inserts a row into the specified table if the value is unique and does not exist in the table already.
///
/// # Arguments
/// * `table_name` - A string slice that holds the name of the table.
/// * `body` - A JSON value containing the data to be inserted.
///
/// ## Example
/// ```
/// # use serde_json::json;
/// # use supabase_rs::SupabaseClient;
/// #[tokio::main]
/// async fn main() {
/// // Initialize the Supabase client
/// let client = SupabaseClient::new("your_supabase_url".to_string(), "your_supabase_key".to_string()).unwrap();
///
/// // This will insert a new row into the table if the value is unique
/// let unique_insert_result = client.insert_if_unique(
/// "your_table_name",
/// json!({"unique_column_name": "unique_value"})
/// ).await;
/// }
/// ```
///
/// # Returns
/// This method returns a `Result<String, String>`. On success, it returns `Ok(String)` with the new row's ID,
/// and on failure, it returns `Err(String)` with an error message indicating a duplicate entry.
pub async fn insert_if_unique(&self, table_name: &str, body: Value) -> Result<String, String> {
let conditions: &serde_json::Map<String, Value> = match body.as_object() {
Some(map) => map,
None => {
println!("\x1b[31mFailed to parse body as JSON object\x1b[0m");
return Err("Failed to parse body as JSON object".to_string());
}
};
// Check if any row in the table matches all the column-value pairs in the body
let mut query: crate::query::QueryBuilder = self.select(table_name);
for (column_name, column_value) in conditions {
// turn column_value into a string before passing it to the query
// ONLY if it's NOT a string
let column_value_str: String = match column_value {
Value::String(s) => s.clone(),
_ => column_value.to_string(),
};
// our query is sensitive to the type of the column value
query = query.eq(column_name, column_value_str.as_str());
}
let response: Result<Vec<Value>, String> = query.execute().await;
// If no existing row matches all conditions, proceed with the insert
if let Ok(results) = response {
if results.is_empty() {
return self.insert(table_name, body).await;
}
} else {
println!("\x1b[31mFailed to execute select query\x1b[0m");
return Err("Failed to execute select query".to_string());
}
Err("Error 409: Duplicate entry. The values you're trying to insert may already exist in a column with a UNIQUE constraint".to_string())
}
/// Inserts new rows into the specified table in bulk.
///
/// # Arguments
/// * `table_name` - A string slice that holds the name of the table.
/// * `body` - A vector of serializable values to be inserted.
///
/// # Example
/// ```ignore
/// // Initialize the Supabase client
/// # use serde_json::{json, Value};
/// # use serde::Serialize;
///
/// // A struct that implements the Serialize trait
/// #[derive(Serialize)]
/// pub struct User {
/// name: String,
/// }
///
/// let client = SupabaseClient::new("your_supabase_url", "your_supabase_key");
///
/// // Create the body of the request as a vector of JSON values
/// let body: Vec<Value> = vec![
/// json!({"column_name": "value"}),
/// json!({"column_name": "value"}),
/// User { name: "Alice".to_string() },
/// ];
///
/// // This will insert a new row into the table
/// let insert_result = client.insert("your_table_name", body).await;
/// ```
///
/// # Returns
/// This method returns a `Result<(), String>`. On success, it returns `Ok(())`,
/// and on failure, it returns `Err(String)` with an error message.
pub async fn bulk_insert<T>(&self, table_name: &str, body: Vec<T>) -> Result<(), String>
where
T: serde::Serialize,
{
let Ok(body) = serde_json::to_value(body) else {
return Err("Failed to serialize body".to_string());
};
let endpoint: String = format!("{}/rest/v1/{}", self.url, table_name);
#[cfg(feature = "nightly")]
use crate::nightly::print_nightly_warning;
#[cfg(feature = "nightly")]
print_nightly_warning();
let response: Response = match self
.client
.post(&endpoint)
.header("apikey", &self.api_key)
.header("Authorization", format!("Bearer {}", &self.api_key))
.header("Content-Type", "application/json")
.header("x_client_info", "supabase-rs/0.3.7")
.body(body.to_string())
.send()
.await
{
Ok(response) => response,
Err(e) => return Err(e.to_string()),
};
if response.status().is_success() {
Ok(())
} else if response.status().as_u16() == 409 {
println!("\x1b[31mError 409: Duplicate entry. The value you're trying to insert may already exist in a column with a UNIQUE constraint.\x1b[0m");
return Err("\x1b[31mError 409: Duplicate entry. The value you're trying to insert may already exist in a column with a UNIQUE constraint.\x1b[0m".to_string());
} else {
println!("\x1b[31mError: {:?}\x1b[0m", response);
return Err(response.status().to_string());
}
}
}