DatabaseProxy Class

An interface to interact with a specific database.

This class should not be instantiated directly. Instead use the get_database_client method to get an existing database, or the create_database method to create a new database.

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:azure.cosmos.aio.CosmosClientConnection>

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 exists 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.

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.

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

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.

async create_container(id: str, partition_key: PartitionKey, *, indexing_policy: Dict[str, str] | None = None, default_ttl: int | None = None, offer_throughput: int | ThroughputProperties | None = None, unique_key_policy: Dict[str, str] | None = None, conflict_resolution_policy: Dict[str, str] | 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, vector_embedding_policy: Dict[str, Any] | 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.

Keyword-Only Parameters

Name Description
indexing_policy

The indexing policy to apply to the container.

default_ttl
int

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

offer_throughput

The provisioned throughput for this offer.

unique_key_policy

The unique key policy to apply to the container.

conflict_resolution_policy

The conflict resolution policy to apply to the container.

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.

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://video2.skills-academy.com/en-us/azure/cosmos-db/nosql/query/computed-properties?tabs=dotnet

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.

vector_embedding_policy

The vector embedding policy for the container. Each vector embedding possesses a predetermined number of dimensions, is associated with an underlying data type, and is generated for a particular distance function.

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 = await 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 = await 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.

async create_container_if_not_exists(id: str, partition_key: PartitionKey, *, indexing_policy: Dict[str, str] | None = None, default_ttl: int | None = None, offer_throughput: int | ThroughputProperties | None = None, unique_key_policy: Dict[str, str] | None = None, conflict_resolution_policy: Dict[str, str] | 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, vector_embedding_policy: Dict[str, Any] | 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.

Keyword-Only Parameters

Name Description
indexing_policy

The indexing policy to apply to the container.

default_ttl
int

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

offer_throughput

The provisioned throughput for this offer.

unique_key_policy

The unique key policy to apply to the container.

conflict_resolution_policy

The conflict resolution policy to apply to the container.

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.

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://video2.skills-academy.com/en-us/azure/cosmos-db/nosql/query/computed-properties?tabs=dotnet

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.

vector_embedding_policy

provisional The vector embedding policy for the container. Each vector embedding possesses a predetermined number of dimensions, is associated with an underlying data type, and is generated for a particular distance function.

Returns

Type Description

A ContainerProxy instance representing the new container.

Exceptions

Type Description

The container 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.

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

Parameters

Name Description
body
Required

A dict 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:
               await database.create_user(dict(id="Walter Harp"))
               print("Created user 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.

async delete_container(container: str | ContainerProxy | Mapping[str, Any], *, 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 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.

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

Parameters

Name Description
user
Required

The ID (name), dict representing the properties or 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 | Dict[str, Any]) -> ContainerProxy

Parameters

Name Description
container
Required

The ID (name), dict representing the properties, or ContainerProxy instance of the container to get.

Keyword-Only Parameters

Name Description
indexing_policy

The indexing policy to apply to the container.

default_ttl
int

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

offer_throughput

The provisioned throughput for this offer.

unique_key_policy

The unique key policy to apply to the container.

conflict_resolution_policy

The conflict resolution policy to apply to the container.

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.

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://video2.skills-academy.com/en-us/azure/cosmos-db/nosql/query/computed-properties?tabs=dotnet

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.

vector_embedding_policy

The vector embedding policy for the container. Each vector embedding possesses a predetermined number of dimensions, is associated with an underlying data type, and is generated for a particular distance function.

Returns

Type Description

A ContainerProxy instance representing the container.

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 exists for the database, an exception is raised.

async 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 exist for the database 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 UserProxy instance of the user to get.

Keyword-Only Parameters

Name Description
indexing_policy

The indexing policy to apply to the container.

default_ttl
int

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

offer_throughput

The provisioned throughput for this offer.

unique_key_policy

The unique key policy to apply to the container.

conflict_resolution_policy

The conflict resolution policy to apply to the container.

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.

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://video2.skills-academy.com/en-us/azure/cosmos-db/nosql/query/computed-properties?tabs=dotnet

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.

vector_embedding_policy

The vector embedding policy for the container. Each vector embedding possesses a predetermined number of dimensions, is associated with an underlying data type, and is generated for a particular distance function.

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(*, session_token: str | None = None, max_item_count: int | None = None, initial_headers: Dict[str, str] | None = None, **kwargs) -> AsyncItemPaged[Dict[str, Any]]

Keyword-Only Parameters

Name Description
max_item_count
int

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

session_token
str

Token for use with Session consistency.

initial_headers

Initial headers to be sent as part of the request.

response_hook
Callable[[Dict[str, str], <xref:AsyncItemPaged>[Dict[str, Any]]], None]

A callable invoked with the response metadata.

Returns

Type Description
<xref:AsyncItemPaged>[Dict[str, Any]]

An AsyncItemPaged 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)
           async 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) -> AsyncItemPaged[Dict[str, Any]]

Keyword-Only Parameters

Name Description
max_item_count
int

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

response_hook
Callable[[Dict[str, str], <xref:AsyncItemPaged>[Dict[str, Any]]], None]

A callable invoked with the response metadata.

Returns

Type Description
<xref:AsyncItemPaged>[Dict[str, Any]]

An AsyncItemPaged 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, *, parameters: List[Dict[str, Any]] | None = None, session_token: str | None = None, max_item_count: int | None = None, initial_headers: Dict[str, str] | None = None, **kwargs: Any) -> AsyncItemPaged[Dict[str, Any]]

Parameters

Name Description
query
Required
str

The Azure Cosmos DB SQL query to execute.

Keyword-Only Parameters

Name Description
parameters

Optional array of parameters to the query. Each parameter is a dict() with 'name' and 'value' keys.

max_item_count
int

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

session_token
str

Token for use with Session consistency.

initial_headers

Initial headers to be sent as part of the request.

response_hook
Callable[[Dict[str, str], <xref:AsyncItemPaged>[Dict[str, Any]]], None]

A callable invoked with the response metadata.

Returns

Type Description
<xref:AsyncItemPaged>[Dict[str, Any]]

An AsyncItemPaged 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) -> AsyncItemPaged[Dict[str, Any]]

Parameters

Name Description
query
Required
str

The Azure Cosmos DB SQL query to execute.

Keyword-Only Parameters

Name Description
parameters

Optional array of parameters to the query. Each parameter is a dict() with 'name' and 'value' keys. Ignored if no query is provided.

max_item_count
int

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

response_hook
Callable[[Dict[str, str], <xref:AsyncItemPaged>[Dict[str, Any]]], None]

A callable invoked with the response metadata.

Returns

Type Description
<xref:AsyncItemPaged>[Dict[str, Any]]

An AsyncItemPaged of user properties (dicts).

Exceptions

Type Description

The container creation failed.

read

Read the database properties.

async read(*, 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

A dict representing the database properties

Exceptions

Type Description

If the given database couldn't 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.

async replace_container(container: str | ContainerProxy | Mapping[str, Any], partition_key: PartitionKey, *, indexing_policy: Dict[str, str] | None = None, default_ttl: int | None = None, conflict_resolution_policy: Dict[str, str] | 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 ContainerProxy instance of the container to be replaced.

partition_key
Required

The partition key to use for the container.

Keyword-Only Parameters

Name Description
indexing_policy

The indexing policy to apply to the container.

default_ttl
int

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

conflict_resolution_policy

The conflict resolution policy to apply to the container.

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)
           await database.replace_container(container, partition_key=PartitionKey(path='/productName'), default_ttl=3600)

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

replace_throughput

Replace the database-level throughput.

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

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

Parameters

Name Description
throughput
Required

The throughput to be set.

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

No throughput properties exist for the database or the throughput properties could not be updated.

replace_user

Replaces the specified user if it exists in the container.

async 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 UserProxy instance of the user to be replaced.

body
Required

A dict 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.

async 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.