Skip to content

Commit 778af83

Browse files
committed
Convert create_database to a builder pattern
1 parent bb3dfa5 commit 778af83

15 files changed

+93
-111
lines changed

sdk/core/src/macros.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/// Creates setter methods
22
///
3-
/// The methods created are of the form `with_$name` that takes an argument of type `$typ`
3+
/// The methods created are of the form `$name` that takes an argument of type `$typ`
44
/// and sets the field $name to result of calling `$transform` with the value of the argument.
55
///
66
/// In other words. The following macro call:

sdk/cosmos/examples/cancellation.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
use azure_core::prelude::*;
21
use azure_cosmos::prelude::*;
32
use stop_token::prelude::*;
43
use stop_token::StopSource;
@@ -19,8 +18,7 @@ async fn main() -> azure_cosmos::Result<()> {
1918
let client = CosmosClient::new(account.clone(), authorization_token.clone(), options);
2019

2120
// Create a new database, and time out if it takes more than 1 second.
22-
let options = CreateDatabaseOptions::new();
23-
let future = client.create_database(Context::new(), "my_database", options);
21+
let future = client.create_database("my_database").into_future();
2422
let deadline = Instant::now() + Duration::from_secs(1);
2523
match future.until(deadline).await {
2624
Ok(Ok(r)) => println!("successful response: {:?}", r),
@@ -36,8 +34,7 @@ async fn main() -> azure_cosmos::Result<()> {
3634
// Clone the stop token for each request.
3735
let stop = source.token();
3836
tokio::spawn(async move {
39-
let options = CreateDatabaseOptions::new();
40-
let future = client.create_database(Context::new(), "my_database", options);
37+
let future = client.create_database("my_database").into_future();
4138
match future.until(stop).await {
4239
Ok(Ok(r)) => println!("successful response: {:?}", r),
4340
Ok(Err(e)) => println!("request was made but failed: {:?}", e),

sdk/cosmos/src/clients/cosmos_client.rs

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -177,23 +177,8 @@ impl CosmosClient {
177177
}
178178

179179
/// Create a database
180-
pub async fn create_database<S: AsRef<str>>(
181-
&self,
182-
ctx: Context,
183-
database_name: S,
184-
options: CreateDatabaseOptions,
185-
) -> crate::Result<CreateDatabaseResponse> {
186-
let mut request = self.prepare_request_pipeline("dbs", http::Method::POST);
187-
188-
let mut pipeline_context = PipelineContext::new(ctx, ResourceType::Databases.into());
189-
190-
options.decorate_request(&mut request, database_name.as_ref())?;
191-
let response = self
192-
.pipeline()
193-
.send(&mut pipeline_context, &mut request)
194-
.await?;
195-
196-
Ok(CreateDatabaseResponse::try_from(response).await?)
180+
pub fn create_database<S: AsRef<str>>(&self, database_name: S) -> CreateDatabaseBuilder {
181+
CreateDatabaseBuilder::new(self.clone(), database_name.as_ref().to_owned())
197182
}
198183

199184
/// List all databases

sdk/cosmos/src/operations/create_database.rs

Lines changed: 62 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,90 @@
1+
use std::future::Future;
2+
use std::pin::Pin;
3+
14
use crate::headers::from_headers::*;
25
use crate::prelude::*;
36
use crate::resources::Database;
47
use crate::ResourceQuota;
58
use azure_core::headers::{etag_from_headers, session_token_from_headers};
6-
use azure_core::{collect_pinned_stream, Request as HttpRequest, Response as HttpResponse};
9+
use azure_core::{collect_pinned_stream, Context, PipelineContext, Response as HttpResponse};
710
use chrono::{DateTime, Utc};
811

912
#[derive(Debug, Clone)]
10-
pub struct CreateDatabaseOptions {
13+
pub struct CreateDatabaseBuilder {
14+
client: CosmosClient,
15+
database_name: String,
1116
consistency_level: Option<ConsistencyLevel>,
17+
context: Context,
1218
}
1319

14-
impl CreateDatabaseOptions {
15-
pub fn new() -> Self {
20+
impl CreateDatabaseBuilder {
21+
pub(crate) fn new(client: CosmosClient, database_name: String) -> Self {
1622
Self {
23+
client,
24+
database_name,
1725
consistency_level: None,
26+
context: Context::new(),
1827
}
1928
}
2029

2130
setters! {
2231
consistency_level: ConsistencyLevel => Some(consistency_level),
32+
context: Context => context,
33+
}
34+
35+
async fn build(self) -> crate::Result<CreateDatabaseResponse> {
36+
let mut request = self
37+
.client
38+
.prepare_request_pipeline("dbs", http::Method::POST);
39+
40+
let mut pipeline_context =
41+
PipelineContext::new(self.context, ResourceType::Databases.into());
42+
43+
let body = CreateDatabaseBody {
44+
id: self.database_name.as_str(),
45+
};
46+
47+
azure_core::headers::add_optional_header2(&self.consistency_level, &mut request)?;
48+
request.set_body(bytes::Bytes::from(serde_json::to_string(&body)?).into());
49+
let response = self
50+
.client
51+
.pipeline()
52+
.send(&mut pipeline_context, &mut request)
53+
.await?;
54+
55+
Ok(CreateDatabaseResponse::try_from(response).await?)
56+
}
57+
58+
pub fn insert<E: Send + Sync + 'static>(&mut self, entity: E) -> &mut Self {
59+
self.context.insert(entity);
60+
self
61+
}
62+
63+
// impl std::future::IntoFuture for CreateDatabaseBuilder {}
64+
pub fn into_future(self) -> CreateDatabase {
65+
CreateDatabase(Box::pin(self.build()))
2366
}
2467
}
2568

26-
impl CreateDatabaseOptions {
27-
pub(crate) fn decorate_request(
28-
&self,
29-
request: &mut HttpRequest,
30-
database_name: &str,
31-
) -> crate::Result<()> {
32-
#[derive(Serialize)]
33-
struct CreateDatabaseRequest<'a> {
34-
pub id: &'a str,
35-
}
36-
let req = CreateDatabaseRequest { id: database_name };
69+
pub struct CreateDatabase(
70+
Pin<Box<dyn Future<Output = crate::Result<CreateDatabaseResponse>> + Send + 'static>>,
71+
);
3772

38-
azure_core::headers::add_optional_header2(&self.consistency_level, request)?;
39-
request.set_body(bytes::Bytes::from(serde_json::to_string(&req)?).into());
40-
Ok(())
73+
impl Future for CreateDatabase {
74+
type Output = crate::Result<CreateDatabaseResponse>;
75+
fn poll(
76+
mut self: std::pin::Pin<&mut Self>,
77+
cx: &mut std::task::Context<'_>,
78+
) -> std::task::Poll<Self::Output> {
79+
Pin::new(&mut self.0).poll(cx)
4180
}
4281
}
4382

83+
#[derive(Serialize)]
84+
struct CreateDatabaseBody<'a> {
85+
pub id: &'a str,
86+
}
87+
4488
#[derive(Debug, Clone, PartialEq, PartialOrd)]
4589
pub struct CreateDatabaseResponse {
4690
pub database: Database,

sdk/cosmos/tests/attachment_00.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,8 @@ async fn attachment() -> Result<(), azure_cosmos::Error> {
3737

3838
// create a temp database
3939
let _create_database_response = client
40-
.create_database(
41-
azure_core::Context::new(),
42-
DATABASE_NAME,
43-
CreateDatabaseOptions::new(),
44-
)
40+
.create_database(DATABASE_NAME)
41+
.into_future()
4542
.await
4643
.unwrap();
4744

sdk/cosmos/tests/collection_operations.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,7 @@ async fn collection_operations() -> Result<(), BoxedError> {
1717
let database_name = "test-collection-operations";
1818
let context = Context::new();
1919

20-
client
21-
.create_database(context.clone(), database_name, CreateDatabaseOptions::new())
22-
.await?;
20+
client.create_database(database_name).into_future().await?;
2321

2422
// create collection!
2523
let db_client = client.clone().into_database_client(database_name.clone());

sdk/cosmos/tests/cosmos_collection.rs

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,8 @@ async fn create_and_delete_collection() {
1414
let client = setup::initialize().unwrap();
1515

1616
client
17-
.create_database(
18-
azure_core::Context::new(),
19-
DATABASE_NAME,
20-
CreateDatabaseOptions::new(),
21-
)
17+
.create_database(DATABASE_NAME)
18+
.into_future()
2219
.await
2320
.unwrap();
2421

@@ -85,11 +82,8 @@ async fn replace_collection() {
8582
const COLLECTION_NAME: &str = "test-collection";
8683

8784
client
88-
.create_database(
89-
azure_core::Context::new(),
90-
DATABASE_NAME,
91-
CreateDatabaseOptions::new(),
92-
)
85+
.create_database(DATABASE_NAME)
86+
.into_future()
9387
.await
9488
.unwrap();
9589

sdk/cosmos/tests/cosmos_database.rs.disabled

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,8 @@ async fn create_and_delete_database() {
2222

2323
// create a new database and check if the number of DBs increased
2424
let database = client
25-
.create_database(
26-
azure_core::Context::new(),
27-
DATABASE_NAME,
28-
CreateDatabaseOptions::new(),
29-
)
25+
.create_database(DATABASE_NAME)
26+
.into_future()
3027
.await
3128
.unwrap();
3229

sdk/cosmos/tests/cosmos_document.rs

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,8 @@ async fn create_and_delete_document() {
3232
let client = setup::initialize().unwrap();
3333

3434
client
35-
.create_database(
36-
azure_core::Context::new(),
37-
DATABASE_NAME,
38-
CreateDatabaseOptions::new(),
39-
)
35+
.create_database(DATABASE_NAME)
36+
.into_future()
4037
.await
4138
.unwrap();
4239

@@ -126,11 +123,8 @@ async fn query_documents() {
126123
let client = setup::initialize().unwrap();
127124

128125
client
129-
.create_database(
130-
azure_core::Context::new(),
131-
DATABASE_NAME,
132-
CreateDatabaseOptions::new(),
133-
)
126+
.create_database(DATABASE_NAME)
127+
.into_future()
134128
.await
135129
.unwrap();
136130
let database_client = client.into_database_client(DATABASE_NAME);
@@ -203,11 +197,8 @@ async fn replace_document() {
203197
let client = setup::initialize().unwrap();
204198

205199
client
206-
.create_database(
207-
azure_core::Context::new(),
208-
DATABASE_NAME,
209-
CreateDatabaseOptions::new(),
210-
)
200+
.create_database(DATABASE_NAME)
201+
.into_future()
211202
.await
212203
.unwrap();
213204
let database_client = client.into_database_client(DATABASE_NAME);

sdk/cosmos/tests/create_database_and_collection.rs

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,7 @@ async fn create_database_and_collection() -> Result<(), BoxedError> {
1919

2020
// create database!
2121
log::info!("Creating a database with name '{}'...", database_name);
22-
let db = client
23-
.create_database(
24-
context.clone(),
25-
&database_name,
26-
CreateDatabaseOptions::new(),
27-
)
28-
.await?;
22+
let db = client.create_database(&database_name).into_future().await?;
2923
log::info!("Successfully created a database");
3024
log::debug!("The create_database response: {:#?}", db);
3125

0 commit comments

Comments
 (0)