Skip to content

Commit

Permalink
add example to create database
Browse files Browse the repository at this point in the history
  • Loading branch information
analogrelay authored Oct 14, 2024
1 parent edbfb84 commit 273b0b0
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 34 deletions.
2 changes: 0 additions & 2 deletions sdk/cosmos/azure_data_cosmos/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ documentation = "https://docs.rs/azure_data_cosmos"
keywords = ["sdk", "azure", "rest", "cloud", "cosmos", "database"]
categories = ["api-bindings"]

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
async-trait.workspace = true
azure_core.workspace = true
Expand Down
90 changes: 64 additions & 26 deletions sdk/cosmos/azure_data_cosmos/examples/cosmos/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,80 @@ use azure_data_cosmos::{
clients::{ContainerClientMethods, DatabaseClientMethods},
CosmosClient, CosmosClientMethods, PartitionKey,
};
use clap::Args;
use clap::{Args, Subcommand};

/// Creates a new item.
#[derive(Clone, Args)]
pub struct CreateCommand {
/// The database in which to create the item.
database: String,
#[command(subcommand)]
subcommand: Subcommands,
}

#[derive(Clone, Subcommand)]
pub enum Subcommands {
/// Create an item in a container.
Item {
/// The database in which to create the item.
database: String,

/// The container in which to create the item.
container: String,

/// The container in which to create the item.
container: String,
/// The partition key of the new item.
#[clap(long, short)]
partition_key: String,

/// The partition key of the new item.
#[clap(long, short)]
partition_key: String,
/// The JSON of the new item.
#[clap(long, short)]
json: String,
},

/// The JSON of the new item.
#[clap(long, short)]
json: String,
/// Create a database (does not support Entra ID).
#[cfg(feature = "control_plane")]
Database {
/// The ID of the new database to create.
id: String,
},
}

impl CreateCommand {
pub async fn run(self, client: CosmosClient) -> Result<(), Box<dyn Error>> {
let db_client = client.database_client(&self.database);
let container_client = db_client.container_client(&self.container);

let pk = PartitionKey::from(&self.partition_key);
let item: serde_json::Value = serde_json::from_str(&self.json)?;

let created = container_client
.create_item(pk, item, None)
.await?
.deserialize_body()
.await?
.unwrap();
println!("Created item:");
println!("{:#?}", created);
Ok(())
match self.subcommand {
Subcommands::Item {
database,
container,
partition_key,
json,
} => {
let db_client = client.database_client(database);
let container_client = db_client.container_client(container);

let pk = PartitionKey::from(&partition_key);
let item: serde_json::Value = serde_json::from_str(&json)?;

let created = container_client
.create_item(pk, item, None)
.await?
.deserialize_body()
.await?
.unwrap();
println!("Created item:");
println!("{:#?}", created);
Ok(())
}

#[cfg(feature = "control_plane")]
Subcommands::Database { id } => {
let db = client
.create_database(id, None)
.await?
.deserialize_body()
.await?
.unwrap();
println!("Created database:");
println!("{:#?}", db);
Ok(())
}
}
}
}
25 changes: 19 additions & 6 deletions sdk/cosmos/azure_data_cosmos/src/clients/cosmos_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,26 @@

use crate::{
clients::DatabaseClient,
models::{DatabaseProperties, DatabaseQueryResults},
models::DatabaseQueryResults,
pipeline::{AuthorizationPolicy, CosmosPipeline, ResourceType},
utils::AppendPathSegments,
CosmosClientOptions, CreateDatabaseOptions, Query, QueryDatabasesOptions,
CosmosClientOptions, Query, QueryDatabasesOptions,
};
use azure_core::{credentials::TokenCredential, Context, Method, Request, Response, Url};
use serde::Serialize;
use azure_core::{credentials::TokenCredential, Request, Url};
use std::sync::Arc;

#[cfg(feature = "control_plane")]
use crate::{
models::{DatabaseProperties, Item},
CreateDatabaseOptions,
};

#[cfg(feature = "control_plane")]
use azure_core::{Context, Method, Response};

#[cfg(feature = "control_plane")]
use serde::Serialize;

#[cfg(feature = "key_auth")]
use azure_core::credentials::Secret;

Expand Down Expand Up @@ -75,12 +86,13 @@ pub trait CosmosClientMethods {
/// # Arguments
/// * `id` - The ID of the new database.
/// * `options` - Optional parameters for the request.
#[allow(async_fn_in_trait)] // REASON: See https://github.com/Azure/azure-sdk-for-rust/issues/1796 for detailed justification
#[cfg(feature = "control_plane")]
async fn create_database(
&self,
id: String,
options: Option<CreateDatabaseOptions>,
) -> azure_core::Result<Response<DatabaseProperties>>;
) -> azure_core::Result<Response<Item<DatabaseProperties>>>;
}

impl CosmosClient {
Expand Down Expand Up @@ -180,14 +192,15 @@ impl CosmosClientMethods for CosmosClient {
.send_query_request(query.into(), base_request, ResourceType::Databases)
}

#[cfg(feature = "control_plane")]
async fn create_database(
&self,
id: String,

#[allow(unused_variables)]
// REASON: This is a documented public API so prefixing with '_' is undesirable.
options: Option<CreateDatabaseOptions>,
) -> azure_core::Result<Response<DatabaseProperties>> {
) -> azure_core::Result<Response<Item<DatabaseProperties>>> {
#[derive(Serialize)]
struct RequestBody {
id: String,
Expand Down
3 changes: 3 additions & 0 deletions sdk/cosmos/azure_data_cosmos/src/options/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License.

mod cosmos_client_options;
#[cfg(feature = "control_plane")]
mod create_database_options;
mod item_options;
mod query_containers_options;
Expand All @@ -11,6 +12,7 @@ mod read_container_options;
mod read_database_options;

pub use cosmos_client_options::CosmosClientOptions;
#[cfg(feature = "control_plane")]
pub use create_database_options::CreateDatabaseOptions;
pub use item_options::ItemOptions;
pub use query_containers_options::QueryContainersOptions;
Expand All @@ -25,6 +27,7 @@ pub mod builders {
//! You shouldn't need to construct these builders on your own. Instead, use the `builder()` method on the related options type to get an instance of the builder.

pub use super::cosmos_client_options::CosmosClientOptionsBuilder;
#[cfg(feature = "control_plane")]
pub use super::create_database_options::CreateDatabaseOptionsBuilder;
pub use super::item_options::ItemOptionsBuilder;
pub use super::query_containers_options::QueryContainersOptionsBuilder;
Expand Down

0 comments on commit 273b0b0

Please sign in to comment.