DatabaseProxy Class

An interface to interact with a specific database.

This class should not be instantiated directly. Instead use the 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: azure.cosmos._cosmos_client_connection.CosmosClientConnection, id: str, properties: Optional[Dict[str, Any]] = None)

Parameters

client_connection
id
properties
default value: None

Variables

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. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: ThroughputProperties for the database. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: 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.

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. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: ThroughputProperties for the database. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: 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_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: Any, indexing_policy: Optional[Dict[str, Any]] = None, default_ttl: Optional[int] = None, populate_query_metrics: Optional[bool] = None, offer_throughput: Optional[int] = None, unique_key_policy: Optional[Dict[str, Any]] = None, conflict_resolution_policy: Optional[Dict[str, Any]] = None, **kwargs: Any) -> azure.cosmos.container.ContainerProxy

Parameters

id
Required

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

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.

session_token
str

Token for use with Session consistency.

initial_headers
dict[<xref:str,str>]

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
MatchConditions

The match condition to use upon the etag.

response_hook
<xref:Callable>

A callable invoked with the response metadata.

analytical_storage_ttl

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.

Returns

A ContainerProxy instance representing the new container.

Return type

Exceptions

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: Any, indexing_policy: Optional[Dict[str, Any]] = None, default_ttl: Optional[int] = None, populate_query_metrics: Optional[bool] = None, offer_throughput: Optional[int] = None, unique_key_policy: Optional[Dict[str, Any]] = None, conflict_resolution_policy: Optional[Dict[str, Any]] = None, **kwargs: Any) -> azure.cosmos.container.ContainerProxy

Parameters

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.

populate_query_metrics
Required

Enable returning query metrics in response headers.

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.

session_token
str

Token for use with Session consistency.

initial_headers
dict[<xref:str,str>]

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
MatchConditions

The match condition to use upon the etag.

response_hook
<xref:Callable>

A callable invoked with the response metadata.

analytical_storage_ttl

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.

Returns

A ContainerProxy instance representing the container.

Return type

Exceptions

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) -> azure.cosmos.user.UserProxy

Parameters

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.

response_hook
<xref:Callable>

A callable invoked with the response metadata.

Returns

A UserProxy instance representing the new user.

Return type

Exceptions

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: Union[str, azure.cosmos.container.ContainerProxy, Dict[str, Any]], populate_query_metrics: Optional[bool] = None, **kwargs: Any) -> None

Parameters

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.

session_token
str

Token for use with Session consistency.

initial_headers
dict[<xref:str,str>]

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
MatchConditions

The match condition to use upon the etag.

response_hook
<xref:Callable>

A callable invoked with the response metadata.

Return type

Exceptions

If the container couldn't be deleted.

delete_user

Delete the specified user from the container.

delete_user(user: Union[str, azure.cosmos.user.UserProxy, Dict[str, Any]], **kwargs: Any) -> None

Parameters

user
Required

The ID (name), dict representing the properties or UserProxy instance of the user to be deleted.

response_hook
<xref:Callable>

A callable invoked with the response metadata.

Return type

Exceptions

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: Union[str, azure.cosmos.container.ContainerProxy, Dict[str, Any]]) -> azure.cosmos.container.ContainerProxy

Parameters

container
Required

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

Returns

A ContainerProxy instance representing the retrieved database.

Return type

Exceptions

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. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: ThroughputProperties for the database. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: No throughput properties exists for the container or

the throughput properties could not be retrieved.

get_throughput(**kwargs: Any) -> azure.cosmos.offer.ThroughputProperties

Return type

Exceptions

The container creation failed.

get_user_client

Get a UserProxy for a user with specified ID.

get_user_client(user: Union[str, azure.cosmos.user.UserProxy, Dict[str, Any]]) -> azure.cosmos.user.UserProxy

Parameters

user
Required

The ID (name), dict representing the properties or UserProxy instance of the user to be retrieved.

Returns

A UserProxy instance representing the retrieved user.

Return type

Exceptions

The container creation failed.

list_containers

List the containers in the database.

list_containers(max_item_count: Optional[int] = None, populate_query_metrics: Optional[bool] = None, **kwargs: Any) -> Iterable[Dict[str, Any]]

Parameters

max_item_count
Required

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

session_token
str

Token for use with Session consistency.

initial_headers
dict[<xref:str,str>]

Initial headers to be sent as part of the request.

response_hook
<xref:Callable>

A callable invoked with the response metadata.

Returns

An Iterable of container properties (dicts).

Return type

<xref:Iterable>[dict[str, <xref:Any>]]

Exceptions

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: Optional[int] = None, **kwargs: Any) -> Iterable[Dict[str, Any]]

Parameters

max_item_count
Required

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

response_hook
<xref:Callable>

A callable invoked with the response metadata.

Returns

An Iterable of user properties (dicts).

Return type

<xref:Iterable>[dict[str, <xref:Any>]]

Exceptions

The container creation failed.

query_containers

List the properties for containers in the current database.

query_containers(query: Optional[str] = None, parameters: Optional[List[str]] = None, max_item_count: Optional[int] = None, populate_query_metrics: Optional[bool] = None, **kwargs: Any) -> Iterable[Dict[str, Any]]

Parameters

query
Required

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

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

session_token
str

Token for use with Session consistency.

initial_headers
dict[<xref:str,str>]

Initial headers to be sent as part of the request.

response_hook
<xref:Callable>

A callable invoked with the response metadata.

Returns

An Iterable of container properties (dicts).

Return type

<xref:Iterable>[dict[str, <xref:Any>]]

Exceptions

The container creation failed.

query_users

Return all users matching the given query.

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

Parameters

query
Required

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

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

response_hook
<xref:Callable>

A callable invoked with the response metadata.

Returns

An Iterable of user properties (dicts).

Return type

<xref:Iterable>[str, <xref:Any>]

Exceptions

The container creation failed.

read

Read the database properties.

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

Parameters

session_token
str

Token for use with Session consistency.

initial_headers
dict[<xref:str,str>]

Initial headers to be sent as part of the request.

response_hook
<xref:Callable>

A callable invoked with the response metadata.

Return type

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

Exceptions

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. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: ThroughputProperties for the database. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: No throughput properties exists for the container or

the throughput properties could not be retrieved.

read_offer(**kwargs: Any) -> azure.cosmos.offer.ThroughputProperties

Return type

Exceptions

The container creation failed.

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: Union[str, azure.cosmos.container.ContainerProxy, Dict[str, Any]], partition_key: Any, indexing_policy: Optional[Dict[str, Any]] = None, default_ttl: Optional[int] = None, conflict_resolution_policy: Optional[Dict[str, Any]] = None, populate_query_metrics: Optional[bool] = None, **kwargs: Any) -> azure.cosmos.container.ContainerProxy

Parameters

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.

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.

conflict_resolution_policy
Required

The conflict resolution policy to apply to the container.

populate_query_metrics
Required

Enable returning query metrics in response headers.

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
MatchConditions

The match condition to use upon the etag.

initial_headers
dict[<xref:str,str>]

Initial headers to be sent as part of the request.

response_hook
<xref:Callable>

A callable invoked with the response metadata.

Returns

A ContainerProxy instance representing the container after replace completed.

Return type

Exceptions

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: Optional[int], **kwargs: Any) -> azure.cosmos.offer.ThroughputProperties

Parameters

throughput
Required

The throughput to be set (an integer).

response_hook
<xref:Callable>

A callable invoked with the response metadata.

Returns

ThroughputProperties for the database, updated with new throughput.

Return type

<xref:<xref:azure.cosmos.Offer If no throughput properties exists for the database>>

,
<xref:<xref:if the throughput properties could not be updated.>>,

Exceptions

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

replace_user

Replaces the specified user if it exists in the container.

replace_user(user: Union[str, azure.cosmos.user.UserProxy, Dict[str, Any]], body: Dict[str, Any], **kwargs: Any) -> azure.cosmos.user.UserProxy

Parameters

user
Required

The ID (name), dict representing the properties or UserProxy instance of the user to be replaced.

body
Required

A dict-like object representing the user to replace.

response_hook
<xref:Callable>

A callable invoked with the response metadata.

Returns

A UserProxy instance representing the user after replace went through.

Return type

Exceptions

If the replace 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) -> azure.cosmos.user.UserProxy

Parameters

body
Required

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

response_hook
<xref:Callable>

A callable invoked with the response metadata.

Returns

A UserProxy instance representing the upserted user.

Return type

Exceptions

If the given user could not be upserted.