DatabaseProxy Class

An interface to interact with a specific database.

This class should not be instantiated directly. Instead use the <xref:CosmosClient.get_database_client> method.

A database contains one or more containers, each of which can contain items, stored procedures, triggers, and user-defined functions.

A database can also have associated users, each of which is configured with a set of permissions for accessing certain containers, stored procedures, triggers, user-defined functions, or items.

An Azure Cosmos DB SQL API database has the following system-generated properties. These properties are read-only:

  • _rid: The resource ID.

  • _ts: When the resource was last updated. The value is a timestamp.

  • _self: The unique addressable URI for the resource.

  • _etag: The resource etag required for optimistic concurrency control.

  • _colls: The addressable path of the collections resource.

  • _users: The addressable path of the users resource.

Inheritance
builtins.object
DatabaseProxy

Constructor

DatabaseProxy(client_connection: CosmosClientConnection, id: str, properties: Dict[str, Any] | None = None)

Parameters

Name Description
client_connection
Required
<xref:ClientSession>

Client from which this database was retrieved.

id
Required
str

ID (name) of the database.

properties
default value: None

Variables

Name Description
id

The ID (name) of the database.

Methods

create_container

Create a new container with the given ID (name).

If a container with the given ID already exists, a CosmosResourceExistsError is raised.

create_container_if_not_exists

Create a container if it does not exist already.

If the container already exists, the existing settings are returned. Note: it does not check or update the existing container settings or offer throughput if they differ from what was passed into the method.

create_user

Create a new user in the container.

To update or replace an existing user, use the <xref:ContainerProxy.upsert_user> method.

delete_container

Delete a container.

delete_user

Delete the specified user from the container.

get_container_client

Get a ContainerProxy for a container with specified ID (name).

get_throughput

Get the ThroughputProperties object for this database.

If no ThroughputProperties already exist for the database, an exception is raised.

get_user_client

Get a UserProxy for a user with specified ID.

list_containers

List the containers in the database.

list_users

List all the users in the container.

query_containers

List the properties for containers in the current database.

query_users

Return all users matching the given query.

read

Read the database properties.

read_offer

Get the ThroughputProperties object for this database.

If no ThroughputProperties already exist for the database, an exception is raised.

replace_container

Reset the properties of the container.

Property changes are persisted immediately. Any properties not specified will be reset to their default values.

replace_throughput

Replace the database-level throughput.

replace_user

Replaces the specified user if it exists in the container.

upsert_user

Insert or update the specified user.

If the user already exists in the container, it is replaced. If the user does not already exist, it is inserted.

create_container

Create a new container with the given ID (name).

If a container with the given ID already exists, a CosmosResourceExistsError is raised.

create_container(id: str, partition_key: PartitionKey, indexing_policy: Dict[str, Any] | None = None, default_ttl: int | None = None, populate_query_metrics: bool | None = None, offer_throughput: int | ThroughputProperties | None = None, unique_key_policy: Dict[str, Any] | None = None, conflict_resolution_policy: Dict[str, Any] | None = None, *, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, etag: str | None = None, match_condition: MatchConditions | None = None, analytical_storage_ttl: int | None = None, **kwargs: Any) -> ContainerProxy

Parameters

Name Description
id
Required
str

ID (name) of container to create.

partition_key
Required

The partition key to use for the container.

indexing_policy
Required

The indexing policy to apply to the container.

default_ttl
Required
int

Default time to live (TTL) for items in the container. If unused, items do not expire.

offer_throughput
Required

The provisioned throughput for this offer.

unique_key_policy
Required

The unique key policy to apply to the container.

conflict_resolution_policy
Required

The conflict resolution policy to apply to the container.

Keyword-Only Parameters

Name Description
session_token
str

Token for use with Session consistency.

initial_headers

Initial headers to be sent as part of the request.

etag
str

An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

match_condition

The match condition to use upon the etag.

response_hook

A callable invoked with the response metadata.

analytical_storage_ttl
int

Analytical store time to live (TTL) for items in the container. A value of None leaves analytical storage off and a value of -1 turns analytical storage on with no TTL. Please note that analytical storage can only be enabled on Synapse Link enabled accounts.

computed_properties

provisional Sets The computed properties for this container in the Azure Cosmos DB Service. For more Information on how to use computed properties visit here: https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/query/computed-properties?tabs=dotnet

Returns

Type Description

A ContainerProxy instance representing the new container.

Exceptions

Type Description

The container creation failed.

Examples

Create a container with default settings:


   container_name = "products"
   try:
       container = database.create_container(
           id=container_name, partition_key=PartitionKey(path="/productName")
       )
   except exceptions.CosmosResourceExistsError:
       container = database.get_container_client(container_name)

Create a container with specific settings; in this case, a custom partition key:


   customer_container_name = "customers"
   try:
       customer_container = database.create_container(
           id=customer_container_name,
           partition_key=PartitionKey(path="/city"),
           default_ttl=200,
       )
   except exceptions.CosmosResourceExistsError:
       customer_container = database.get_container_client(customer_container_name)

create_container_if_not_exists

Create a container if it does not exist already.

If the container already exists, the existing settings are returned. Note: it does not check or update the existing container settings or offer throughput if they differ from what was passed into the method.

create_container_if_not_exists(id: str, partition_key: PartitionKey, indexing_policy: Dict[str, Any] | None = None, default_ttl: int | None = None, populate_query_metrics: bool | None = None, offer_throughput: int | ThroughputProperties | None = None, unique_key_policy: Dict[str, Any] | None = None, conflict_resolution_policy: Dict[str, Any] | None = None, *, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, etag: str | None = None, match_condition: MatchConditions | None = None, analytical_storage_ttl: int | None = None, **kwargs: Any) -> ContainerProxy

Parameters

Name Description
id
Required

ID (name) of container to read or create.

partition_key
Required

The partition key to use for the container.

indexing_policy
Required

The indexing policy to apply to the container.

default_ttl
Required

Default time to live (TTL) for items in the container. If unspecified, items do not expire.

offer_throughput
Required

The provisioned throughput for this offer.

unique_key_policy
Required

The unique key policy to apply to the container.

conflict_resolution_policy
Required

The conflict resolution policy to apply to the container.

Keyword-Only Parameters

Name Description
session_token
str

Token for use with Session consistency.

initial_headers

Initial headers to be sent as part of the request.

etag
str

An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

match_condition

The match condition to use upon the etag.

response_hook

A callable invoked with the response metadata.

analytical_storage_ttl
int

Analytical store time to live (TTL) for items in the container. A value of None leaves analytical storage off and a value of -1 turns analytical storage on with no TTL. Please note that analytical storage can only be enabled on Synapse Link enabled accounts.

computed_properties

provisional Sets The computed properties for this container in the Azure Cosmos DB Service. For more Information on how to use computed properties visit here: https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/query/computed-properties?tabs=dotnet

Returns

Type Description

A ContainerProxy instance representing the container.

Exceptions

Type Description

The container read or creation failed.

create_user

Create a new user in the container.

To update or replace an existing user, use the <xref:ContainerProxy.upsert_user> method.

create_user(body: Dict[str, Any], **kwargs: Any) -> UserProxy

Parameters

Name Description
body
Required

A dict-like object with an id key and value representing the user to be created. The user ID must be unique within the database, and consist of no more than 255 characters.

Keyword-Only Parameters

Name Description
response_hook

A callable invoked with the response metadata.

Returns

Type Description

A UserProxy instance representing the new user.

Exceptions

Type Description

If the given user couldn't be created.

Examples

Create a database user:


   try:
       database.create_user(dict(id="Walter Harp"))
   except exceptions.CosmosResourceExistsError:
       print("A user with that ID already exists.")
   except exceptions.CosmosHttpResponseError as failure:
       print("Failed to create user. Status code:{}".format(failure.status_code))

delete_container

Delete a container.

delete_container(container: str | ContainerProxy | Mapping[str, Any], populate_query_metrics: bool | None = None, *, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, etag: str | None = None, match_condition: MatchConditions | None = None, **kwargs: Any) -> None

Parameters

Name Description
container
Required

The ID (name) of the container to delete. You can either pass in the ID of the container to delete, a <xref:azure.cosmos.database.ContainerProxy> instance or a dict representing the properties of the container.

Keyword-Only Parameters

Name Description
session_token
str

Token for use with Session consistency.

initial_headers

Initial headers to be sent as part of the request.

etag
str

An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

match_condition

The match condition to use upon the etag.

response_hook

A callable invoked with the response metadata.

Returns

Type Description

Exceptions

Type Description

If the container couldn't be deleted.

delete_user

Delete the specified user from the container.

delete_user(user: str | UserProxy | Mapping[str, Any], **kwargs: Any) -> None

Parameters

Name Description
user
Required

The ID (name), dict representing the properties or <xref:azure.cosmos.database.UserProxy> instance of the user to be deleted.

Keyword-Only Parameters

Name Description
response_hook

A callable invoked with the response metadata.

Returns

Type Description

Exceptions

Type Description

The user wasn't deleted successfully.

The user does not exist in the container.

get_container_client

Get a ContainerProxy for a container with specified ID (name).

get_container_client(container: str | ContainerProxy | Mapping[str, Any]) -> ContainerProxy

Parameters

Name Description
container
Required

The ID (name) of the container, a <xref:azure.cosmos.database.ContainerProxy> instance, or a dict representing the properties of the container to be retrieved.

Keyword-Only Parameters

Name Description
session_token
str

Token for use with Session consistency.

initial_headers

Initial headers to be sent as part of the request.

etag
str

An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

match_condition

The match condition to use upon the etag.

response_hook

A callable invoked with the response metadata.

analytical_storage_ttl
int

Analytical store time to live (TTL) for items in the container. A value of None leaves analytical storage off and a value of -1 turns analytical storage on with no TTL. Please note that analytical storage can only be enabled on Synapse Link enabled accounts.

computed_properties

provisional Sets The computed properties for this container in the Azure Cosmos DB Service. For more Information on how to use computed properties visit here: https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/query/computed-properties?tabs=dotnet

Returns

Type Description

A ContainerProxy instance representing the retrieved database.

Exceptions

Type Description

The container creation failed.

Examples

Get an existing container, handling a failure if encountered:


   database = client.get_database_client(database_name)
   container = database.get_container_client(container_name)

get_throughput

Get the ThroughputProperties object for this database.

If no ThroughputProperties already exist for the database, an exception is raised.

get_throughput(**kwargs: Any) -> ThroughputProperties

Keyword-Only Parameters

Name Description
response_hook

A callable invoked with the response metadata.

Returns

Type Description

ThroughputProperties for the database.

Exceptions

Type Description

No throughput properties exists for the container or the throughput properties could not be retrieved.

get_user_client

Get a UserProxy for a user with specified ID.

get_user_client(user: str | UserProxy | Mapping[str, Any]) -> UserProxy

Parameters

Name Description
user
Required

The ID (name), dict representing the properties or <xref:azure.cosmos.database.UserProxy> instance of the user to be retrieved.

Keyword-Only Parameters

Name Description
session_token
str

Token for use with Session consistency.

initial_headers

Initial headers to be sent as part of the request.

etag
str

An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

match_condition

The match condition to use upon the etag.

response_hook

A callable invoked with the response metadata.

analytical_storage_ttl
int

Analytical store time to live (TTL) for items in the container. A value of None leaves analytical storage off and a value of -1 turns analytical storage on with no TTL. Please note that analytical storage can only be enabled on Synapse Link enabled accounts.

computed_properties

provisional Sets The computed properties for this container in the Azure Cosmos DB Service. For more Information on how to use computed properties visit here: https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/query/computed-properties?tabs=dotnet

Returns

Type Description

A UserProxy instance representing the retrieved user.

Exceptions

Type Description

The container creation failed.

list_containers

List the containers in the database.

list_containers(max_item_count: int | None = None, populate_query_metrics: bool | None = None, *, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, **kwargs: Any) -> ItemPaged[Dict[str, Any]]

Parameters

Name Description
max_item_count
Required
int

Max number of items to be returned in the enumeration operation.

Keyword-Only Parameters

Name Description
session_token
str

Token for use with Session consistency.

initial_headers

Initial headers to be sent as part of the request.

response_hook

A callable invoked with the response metadata.

Returns

Type Description

An Iterable of container properties (dicts).

Exceptions

Type Description

The container creation failed.

Examples

List all containers in the database:


   database = client.get_database_client(database_name)
   for container in database.list_containers():
       print("Container ID: {}".format(container['id']))

list_users

List all the users in the container.

list_users(max_item_count: int | None = None, **kwargs: Any) -> ItemPaged[Dict[str, Any]]

Parameters

Name Description
max_item_count
Required
int

Max number of users to be returned in the enumeration operation.

Keyword-Only Parameters

Name Description
response_hook

A callable invoked with the response metadata.

Returns

Type Description

An Iterable of user properties (dicts).

Exceptions

Type Description

The container creation failed.

query_containers

List the properties for containers in the current database.

query_containers(query: str | None = None, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, populate_query_metrics: bool | None = None, *, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, **kwargs: Any) -> ItemPaged[Dict[str, Any]]

Parameters

Name Description
query
Required
str

The Azure Cosmos DB SQL query to execute.

parameters
Required

Optional array of parameters to the query. Ignored if no query is provided.

max_item_count
Required
int

Max number of items to be returned in the enumeration operation.

Keyword-Only Parameters

Name Description
session_token
str

Token for use with Session consistency.

initial_headers

Initial headers to be sent as part of the request.

response_hook

A callable invoked with the response metadata.

Returns

Type Description

An Iterable of container properties (dicts).

Exceptions

Type Description

The container creation failed.

query_users

Return all users matching the given query.

query_users(query: str, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, **kwargs: Any) -> ItemPaged[Dict[str, Any]]

Parameters

Name Description
query
Required
str

The Azure Cosmos DB SQL query to execute.

parameters
Required

Optional array of parameters to the query. Ignored if no query is provided.

max_item_count
Required
int

Max number of users to be returned in the enumeration operation.

Keyword-Only Parameters

Name Description
response_hook

A callable invoked with the response metadata.

Returns

Type Description

An Iterable of user properties (dicts).

Exceptions

Type Description

The container creation failed.

read

Read the database properties.

read(populate_query_metrics: bool | None = None, *, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, **kwargs: Any) -> Dict[str, Any]

Keyword-Only Parameters

Name Description
session_token
str

Token for use with Session consistency.

initial_headers

Initial headers to be sent as part of the request.

response_hook

A callable invoked with the response metadata.

Returns

Type Description
Dict[<xref:Str>, Any]

A dict representing the database properties.

Exceptions

Type Description

If the given database couldn't be retrieved.

read_offer

Get the ThroughputProperties object for this database.

If no ThroughputProperties already exist for the database, an exception is raised.

read_offer(**kwargs: Any) -> ThroughputProperties

Keyword-Only Parameters

Name Description
response_hook

A callable invoked with the response metadata.

Returns

Type Description

ThroughputProperties for the database.

Exceptions

Type Description

No throughput properties exists for the container or the throughput properties could not be retrieved.

replace_container

Reset the properties of the container.

Property changes are persisted immediately. Any properties not specified will be reset to their default values.

replace_container(container: str | ContainerProxy | Mapping[str, Any], partition_key: PartitionKey, indexing_policy: Dict[str, Any] | None = None, default_ttl: int | None = None, conflict_resolution_policy: Dict[str, Any] | None = None, populate_query_metrics: bool | None = None, *, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, etag: str | None = None, match_condition: MatchConditions | None = None, analytical_storage_ttl: int | None = None, **kwargs: Any) -> ContainerProxy

Parameters

Name Description
container
Required

The ID (name), dict representing the properties or <xref:azure.cosmos.database.ContainerProxy> instance of the container to be replaced.

partition_key
Required

The partition key to use for the container.

indexing_policy
Required

The indexing policy to apply to the container.

default_ttl
Required
int

Default time to live (TTL) for items in the container. If unspecified, items do not expire.

conflict_resolution_policy
Required

The conflict resolution policy to apply to the container.

Keyword-Only Parameters

Name Description
session_token
str

Token for use with Session consistency.

etag
str

An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

match_condition

The match condition to use upon the etag.

initial_headers

Initial headers to be sent as part of the request.

analytical_storage_ttl
int

Analytical store time to live (TTL) for items in the container. A value of None leaves analytical storage off and a value of -1 turns analytical storage on with no TTL. Please note that analytical storage can only be enabled on Synapse Link enabled accounts.

response_hook

A callable invoked with the response metadata.

Returns

Type Description

A ContainerProxy instance representing the container after replace completed.

Exceptions

Type Description

Raised if the container couldn't be replaced. This includes if the container with given id does not exist.

Examples

Reset the TTL property on a container, and display the updated properties:


   # Set the TTL on the container to 3600 seconds (one hour)
   database.replace_container(container, partition_key=PartitionKey(path='/productName'), default_ttl=3600)

   # Display the new TTL setting for the container
   container_props = database.get_container_client(container_name).read()
   print("New container TTL: {}".format(json.dumps(container_props['defaultTtl'])))

replace_throughput

Replace the database-level throughput.

replace_throughput(throughput: int | ThroughputProperties, **kwargs: Any) -> ThroughputProperties

Parameters

Name Description
throughput
Required

The throughput to be set (an integer).

Keyword-Only Parameters

Name Description
response_hook

A callable invoked with the response metadata.

Returns

Type Description

ThroughputProperties for the database, updated with new throughput.

Exceptions

Type Description

If no throughput properties exists for the database or if the throughput properties could not be updated.

replace_user

Replaces the specified user if it exists in the container.

replace_user(user: str | UserProxy | Mapping[str, Any], body: Dict[str, Any], **kwargs: Any) -> UserProxy

Parameters

Name Description
user
Required

The ID (name), dict representing the properties or <xref:azure.cosmos.database.UserProxy> instance of the user to be replaced.

body
Required

A dict-like object representing the user to replace.

Keyword-Only Parameters

Name Description
response_hook

A callable invoked with the response metadata.

Returns

Type Description

A UserProxy instance representing the user after replace went through.

Exceptions

Type Description

If the replace operation failed or the user with given ID does not exist.

upsert_user

Insert or update the specified user.

If the user already exists in the container, it is replaced. If the user does not already exist, it is inserted.

upsert_user(body: Dict[str, Any], **kwargs: Any) -> UserProxy

Parameters

Name Description
body
Required

A dict-like object representing the user to update or insert.

Keyword-Only Parameters

Name Description
response_hook

A callable invoked with the response metadata.

Returns

Type Description

A UserProxy instance representing the upserted user.

Exceptions

Type Description

If the given user could not be upserted.