feat: Add new gcloud commands, API clients, and third-party libraries across various services.

This commit is contained in:
2026-01-01 20:26:35 +01:00
parent 5e23cbece0
commit a19e592eb7
25221 changed files with 8324611 additions and 0 deletions

View File

@@ -0,0 +1,73 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Useful commands for interacting with the Cloud Firestore Admin API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.util import apis
FIRESTORE_API_VERSION = 'v1'
def GetMessages():
"""Import and return the appropriate admin messages module."""
return apis.GetMessagesModule('firestore', FIRESTORE_API_VERSION)
def GetClient():
"""Returns the Cloud Firestore client for the appropriate release track."""
return apis.GetClientInstance('firestore', FIRESTORE_API_VERSION)
def FormatDurationString(duration):
"""Returns the duration string.
Args:
duration: the duration, an int. The unit is seconds.
Returns:
a duration with string format.
"""
return '{}s'.format(duration)
def ParseTagsForTagsValue(tags, tags_value_message_type):
"""Returns the TagsValue message.
Args:
tags: the tags, a dictionary.
tags_value_message_type: the TagsValue message type.
Returns:
a TagsValue message.
"""
tags_value = None
if tags:
additional_properties = [
tags_value_message_type.AdditionalProperty(
key=key, value=value
)
for key, value in tags.items()
]
tags_value = (
tags_value_message_type(
additionalProperties=additional_properties
)
)
return tags_value

View File

@@ -0,0 +1,219 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Useful commands for interacting with the Cloud Firestore Backup Schedules API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.firestore import api_utils
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import exceptions as ex
def _GetBackupSchedulesService():
"""Returns the service to interact with the Firestore Backup Schedules."""
return api_utils.GetClient().projects_databases_backupSchedules
def GetBackupSchedule(project, database, backup_schedule):
"""Gets a backup schedule.
Args:
project: the project of the database of the backup schedule, a string.
database: the database id of the backup schedule, a string.
backup_schedule: the backup schedule to read, a string.
Returns:
a backup schedule.
"""
messages = api_utils.GetMessages()
return _GetBackupSchedulesService().Get(
messages.FirestoreProjectsDatabasesBackupSchedulesGetRequest(
name='projects/{}/databases/{}/backupSchedules/{}'.format(
project,
database,
backup_schedule,
),
)
)
def ListBackupSchedules(project, database):
"""Lists backup schedules under a database.
Args:
project: the project of the database of the backup schedule, a string.
database: the database id of the backup schedule, a string.
Returns:
a list of backup schedules.
"""
messages = api_utils.GetMessages()
return list(
_GetBackupSchedulesService()
.List(
messages.FirestoreProjectsDatabasesBackupSchedulesListRequest(
parent='projects/{}/databases/{}'.format(
project,
database,
),
)
)
.backupSchedules
)
def DeleteBackupSchedule(project, database, backup_schedule):
"""Deletes a backup schedule.
Args:
project: the project of the database of the backup schedule, a string.
database: the database id of the backup schedule, a string.
backup_schedule: the backup schedule to delete, a string.
Returns:
Empty response message.
"""
messages = api_utils.GetMessages()
return _GetBackupSchedulesService().Delete(
messages.FirestoreProjectsDatabasesBackupSchedulesDeleteRequest(
name='projects/{}/databases/{}/backupSchedules/{}'.format(
project,
database,
backup_schedule,
),
)
)
def UpdateBackupSchedule(project, database, backup_schedule, retention):
"""Updates a backup schedule.
Args:
project: the project of the database of the backup schedule, a string.
database: the database id of the backup schedule, a string.
backup_schedule: the backup to read, a string.
retention: the retention of the backup schedule, an int. At what relative
time in the future, compared to the creation time of the backup should the
backup be deleted. The unit is seconds.
Returns:
a backup schedule.
"""
messages = api_utils.GetMessages()
backup_schedule_updates = messages.GoogleFirestoreAdminV1BackupSchedule()
if retention:
backup_schedule_updates.retention = api_utils.FormatDurationString(
retention
)
return _GetBackupSchedulesService().Patch(
messages.FirestoreProjectsDatabasesBackupSchedulesPatchRequest(
name='projects/{}/databases/{}/backupSchedules/{}'.format(
project,
database,
backup_schedule,
),
googleFirestoreAdminV1BackupSchedule=backup_schedule_updates,
)
)
def CreateBackupSchedule(
project, database, retention, recurrence, day_of_week=None
):
"""Creates a backup schedule.
Args:
project: the project of the database of the backup schedule, a string.
database: the database id of the backup schedule, a string.
retention: the retention of the backup schedule, an int. At what relative
time in the future, compared to the creation time of the backup should the
backup be deleted. The unit is seconds.
recurrence: the recurrence of the backup schedule, a string. The valid
values are: daily and weekly.
day_of_week: day of week for weekly backup schdeule.
Returns:
a backup schedule.
Raises:
InvalidArgumentException: if recurrence is invalid.
ConflictingArgumentsException: if recurrence is daily but day-of-week is
provided.
RequiredArgumentException: if recurrence is weekly but day-of-week is not
provided.
"""
messages = api_utils.GetMessages()
backup_schedule = messages.GoogleFirestoreAdminV1BackupSchedule()
backup_schedule.retention = api_utils.FormatDurationString(retention)
if recurrence == 'daily':
if day_of_week is not None:
raise ex.ConflictingArgumentsException(
'--day-of-week',
'Cannot set day of week for daily backup schedules.',
)
backup_schedule.dailyRecurrence = (
messages.GoogleFirestoreAdminV1DailyRecurrence()
)
elif recurrence == 'weekly':
if day_of_week is None:
raise ex.RequiredArgumentException(
'--day-of-week',
'Day of week is required for weekly backup schedules, please use'
' --day-of-week to specify this value',
)
backup_schedule.weeklyRecurrence = (
messages.GoogleFirestoreAdminV1WeeklyRecurrence()
)
backup_schedule.weeklyRecurrence.day = ConvertDayOfWeek(day_of_week)
else:
raise ex.InvalidArgumentException(
'--recurrence',
'invalid recurrence: {}. The available values are: `daily` and'
' `weekly`.'.format(recurrence),
)
return _GetBackupSchedulesService().Create(
messages.FirestoreProjectsDatabasesBackupSchedulesCreateRequest(
parent='projects/{}/databases/{}'.format(
project,
database,
),
googleFirestoreAdminV1BackupSchedule=backup_schedule,
)
)
def ConvertDayOfWeek(day):
"""Converts the user-given day-of-week into DayValueValuesEnum.
Args:
day: day of Week for weekly backup schdeule.
Returns:
DayValueValuesEnum.
Raises:
ValueError: if it is an invalid input.
"""
day_num = arg_parsers.DayOfWeek.DAYS.index(day)
messages = api_utils.GetMessages().GoogleFirestoreAdminV1WeeklyRecurrence()
# a special case for SUN.
if day_num == 0:
day_num = 7
return messages.DayValueValuesEnum(day_num)

View File

@@ -0,0 +1,90 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Useful commands for interacting with the Cloud Firestore Backups API."""
from googlecloudsdk.api_lib.firestore import api_utils
from googlecloudsdk.core import log
def _GetBackupService():
"""Returns the service for interacting with the Firestore Backup service."""
return api_utils.GetClient().projects_locations_backups
def ListBackups(project, location):
"""Lists backups available to Google Cloud Firestore.
Args:
project: the project id to list backups, a string.
location: the location to list backups, a string.
Returns:
a List of Backups.
"""
result = _GetBackupService().List(
api_utils.GetMessages().FirestoreProjectsLocationsBackupsListRequest(
parent='projects/{}/locations/{}'.format(project, location)
)
)
if result.unreachable:
for unreachable in result.unreachable:
log.status.Print(
f'Failed to list backups for location {unreachable}, please retry'
' with command gcloud {version} firestore backups list'
f' --location={unreachable} to get a more concrete error'
)
return list(result.backups)
def GetBackup(project, location, backup):
"""Gets backup with the given name.
Args:
project: the project id to get backup, a string.
location: the location to get backup, a string.
backup: the backup id to get backup, a string.
Returns:
A Backup.
"""
return _GetBackupService().Get(
api_utils.GetMessages().FirestoreProjectsLocationsBackupsGetRequest(
name='projects/{}/locations/{}/backups/{}'.format(
project, location, backup
)
)
)
def DeleteBackup(project, location, backup):
"""Deletes backup with the given name.
Args:
project: the project id to get backup, a string.
location: the location to get backup, a string.
backup: the backup id to get backup, a string.
Returns:
Empty.
"""
return _GetBackupService().Delete(
api_utils.GetMessages().FirestoreProjectsLocationsBackupsDeleteRequest(
name='projects/{}/locations/{}/backups/{}'.format(
project, location, backup
)
)
)

View File

@@ -0,0 +1,79 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Useful commands for interacting with the Cloud Firestore Bulk Delete API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.firestore import api_utils
def _GetDatabaseService():
"""Returns the service for interacting with the Datastore Admin service."""
return api_utils.GetClient().projects_databases
def GetBulkDeleteDocumentsRequest(
database, namespace_ids=None, collection_ids=None
):
"""Returns a request for a Firestore Admin Bulk Delete.
Args:
database: the database id to bulk delete, a string.
namespace_ids: a string list of namespace ids to delete.
collection_ids: a string list of collection ids to delete.
Returns:
a BulkDeleteDocumentsRequest message.
"""
messages = api_utils.GetMessages()
request_class = messages.GoogleFirestoreAdminV1BulkDeleteDocumentsRequest
kwargs = {}
if collection_ids:
kwargs['collectionIds'] = collection_ids
if namespace_ids:
kwargs['namespaceIds'] = namespace_ids
bulk_delete_request = request_class(**kwargs)
return messages.FirestoreProjectsDatabasesBulkDeleteDocumentsRequest(
name=database,
googleFirestoreAdminV1BulkDeleteDocumentsRequest=bulk_delete_request,
)
def BulkDelete(project, database, namespace_ids, collection_ids):
"""Performs a Firestore Admin v1 Bulk Delete.
Args:
project: the project id, a string.
database: the databae id, a string.
namespace_ids: a string list of namespace ids to bulk delete.
collection_ids: a string list of collections to bulk delete.
Returns:
an Operation.
"""
dbname = 'projects/{}/databases/{}'.format(project, database)
return _GetDatabaseService().BulkDeleteDocuments(
GetBulkDeleteDocumentsRequest(
database=dbname,
namespace_ids=namespace_ids,
collection_ids=collection_ids,
)
)

View File

@@ -0,0 +1,230 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Useful commands for interacting with the Cloud Firestore Databases API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.firestore import api_utils
def _GetDatabaseService():
"""Returns the service for interacting with the Firestore admin service."""
return api_utils.GetClient().projects_databases
def GetDatabase(project, database):
"""Performs a Firestore Admin v1 Database Get.
Args:
project: the project id to get, a string.
database: the database id to get, a string.
Returns:
a database.
"""
messages = api_utils.GetMessages()
return _GetDatabaseService().Get(
messages.FirestoreProjectsDatabasesGetRequest(
name='projects/{}/databases/{}'.format(project, database),
)
)
def CreateDatabase(
project,
location,
database,
database_type,
database_edition,
delete_protection_state,
pitr_state,
cmek_config,
mongodb_compatible_data_access_mode,
firestore_data_access_mode,
realtime_updates_mode,
tags=None,
):
"""Performs a Firestore Admin v1 Database Creation.
Args:
project: the project id to create, a string.
location: the database location to create, a string.
database: the database id to create, a string.
database_type: the database type, an Enum.
database_edition: the database edition, an Enum.
delete_protection_state: the value for deleteProtectionState, an Enum.
pitr_state: the value for PitrState, an Enum.
cmek_config: the CMEK config used to encrypt the database, an object.
mongodb_compatible_data_access_mode: The MongoDB compatible API data access
mode to use for this database, an Enum.
firestore_data_access_mode: The Firestore API data access mode to use for
this database, an Enum.
realtime_updates_mode: The Realtime Updates mode to use for this database,
an Enum.
tags: the tags to attach to the database, a key-value dictionary, or None.
Returns:
an Operation.
"""
messages = api_utils.GetMessages()
tags_value = api_utils.ParseTagsForTagsValue(
tags, messages.GoogleFirestoreAdminV1Database.TagsValue
)
return _GetDatabaseService().Create(
messages.FirestoreProjectsDatabasesCreateRequest(
parent='projects/{}'.format(project),
databaseId=database,
googleFirestoreAdminV1Database=messages.GoogleFirestoreAdminV1Database(
type=database_type,
databaseEdition=database_edition,
locationId=location,
deleteProtectionState=delete_protection_state,
pointInTimeRecoveryEnablement=pitr_state,
cmekConfig=cmek_config,
mongodbCompatibleDataAccessMode=mongodb_compatible_data_access_mode,
firestoreDataAccessMode=firestore_data_access_mode,
realtimeUpdatesMode=realtime_updates_mode,
tags=tags_value,
),
)
)
def DeleteDatabase(project, database, etag):
"""Performs a Firestore Admin v1 Database Deletion.
Args:
project: the project of the database to delete, a string.
database: the database id to delete, a string.
etag: the current etag of the Database, a string.
Returns:
an Operation.
"""
messages = api_utils.GetMessages()
return _GetDatabaseService().Delete(
messages.FirestoreProjectsDatabasesDeleteRequest(
name='projects/{}/databases/{}'.format(project, database),
etag=etag,
)
)
def ListDatabases(project, show_deleted):
"""Lists all Firestore databases under the project.
Args:
project: the project ID to list databases, a string.
show_deleted: if true, also returns deleted resources, a boolean.
Returns:
a List of Databases.
"""
messages = api_utils.GetMessages()
return list(
_GetDatabaseService()
.List(
messages.FirestoreProjectsDatabasesListRequest(
parent='projects/{}'.format(project),
showDeleted=True if show_deleted else None,
)
)
.databases
)
def RestoreDatabase(
project,
source_backup,
destination_database,
encryption_config,
tags=None,
):
"""Restores a Firestore database from a backup.
Args:
project: the project ID to list databases, a string.
source_backup: the backup to restore from, a string.
destination_database: the database to restore to, a string.
encryption_config: the encryption config to use for the restored database,
an optional object.
tags: the tags to attach to the database, a key-value dictionary.
Returns:
an Operation.
"""
messages = api_utils.GetMessages()
tags_value = api_utils.ParseTagsForTagsValue(
tags, messages.GoogleFirestoreAdminV1RestoreDatabaseRequest.TagsValue
)
restore_request = messages.GoogleFirestoreAdminV1RestoreDatabaseRequest(
backup=source_backup,
databaseId=destination_database,
encryptionConfig=encryption_config,
tags=tags_value,
)
return _GetDatabaseService().Restore(
messages.FirestoreProjectsDatabasesRestoreRequest(
parent='projects/{}'.format(project),
googleFirestoreAdminV1RestoreDatabaseRequest=restore_request,
)
)
def CloneDatabase(
project,
source_database,
snapshot_time,
destination_database,
encryption_config,
tags=None,
):
"""Clones one Firestore database from another.
Args:
project: the project ID containing the source database, a string.
source_database: the resource name of the database to clone, a string.
snapshot_time: the timestamp at which to clone, a DateTime.
destination_database: the database to clone to, a string.
encryption_config: the encryption config to use for the cloned database, an
optional object.
tags: the tags to attach to the database, a key-value dictionary, or None.
Returns:
an Operation.
"""
messages = api_utils.GetMessages()
tags_value = api_utils.ParseTagsForTagsValue(
tags, messages.GoogleFirestoreAdminV1CloneDatabaseRequest.TagsValue
)
clone_request = messages.GoogleFirestoreAdminV1CloneDatabaseRequest(
pitrSnapshot=messages.GoogleFirestoreAdminV1PitrSnapshot(
database=source_database,
snapshotTime=snapshot_time,
),
databaseId=destination_database,
encryptionConfig=encryption_config,
tags=tags_value,
)
return _GetDatabaseService().Clone(
messages.FirestoreProjectsDatabasesCloneRequest(
parent='projects/{}'.format(project),
googleFirestoreAdminV1CloneDatabaseRequest=clone_request,
)
)

View File

@@ -0,0 +1,149 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Useful commands for interacting with the Cloud Firestore Import/Export API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.firestore import api_utils
def _GetDatabaseService():
"""Returns the service for interacting with the Datastore Admin service."""
return api_utils.GetClient().projects_databases
def GetExportDocumentsRequest(
database,
output_uri_prefix,
namespace_ids=None,
collection_ids=None,
snapshot_time=None,
):
"""Returns a request for a Firestore Admin Export.
Args:
database: the database id to export, a string.
output_uri_prefix: the output GCS path prefix, a string.
namespace_ids: a string list of namespace ids to export.
collection_ids: a string list of collection ids to export.
snapshot_time: the version of the database to export, as string in
google-datetime format.
Returns:
an ExportDocumentsRequest message.
"""
messages = api_utils.GetMessages()
export_request = messages.GoogleFirestoreAdminV1ExportDocumentsRequest(
outputUriPrefix=output_uri_prefix,
namespaceIds=namespace_ids if namespace_ids else [],
collectionIds=collection_ids if collection_ids else [],
snapshotTime=snapshot_time,
)
request = messages.FirestoreProjectsDatabasesExportDocumentsRequest(
name=database, googleFirestoreAdminV1ExportDocumentsRequest=export_request
)
return request
def GetImportDocumentsRequest(
database, input_uri_prefix, namespace_ids=None, collection_ids=None
):
"""Returns a request for a Firestore Admin Import.
Args:
database: the database id to import, a string.
input_uri_prefix: the location of the GCS export files, a string.
namespace_ids: a string list of namespace ids to import.
collection_ids: a string list of collection ids to import.
Returns:
an ImportDocumentsRequest message.
"""
messages = api_utils.GetMessages()
request_class = messages.GoogleFirestoreAdminV1ImportDocumentsRequest
kwargs = {'inputUriPrefix': input_uri_prefix}
if collection_ids:
kwargs['collectionIds'] = collection_ids
if namespace_ids:
kwargs['namespaceIds'] = namespace_ids
import_request = request_class(**kwargs)
return messages.FirestoreProjectsDatabasesImportDocumentsRequest(
name=database, googleFirestoreAdminV1ImportDocumentsRequest=import_request
)
def Export(
project,
database,
output_uri_prefix,
namespace_ids,
collection_ids,
snapshot_time,
):
"""Performs a Firestore Admin Export.
Args:
project: the project id to export, a string.
database: the databae id to import, a string.
output_uri_prefix: the output GCS path prefix, a string.
namespace_ids: a string list of namespace ids to import.
collection_ids: a string list of collections to export.
snapshot_time: the version of the database to export, as string in
google-datetime format.
Returns:
an Operation.
"""
dbname = 'projects/{}/databases/{}'.format(project, database)
return _GetDatabaseService().ExportDocuments(
GetExportDocumentsRequest(
database=dbname,
output_uri_prefix=output_uri_prefix,
namespace_ids=namespace_ids,
collection_ids=collection_ids,
snapshot_time=snapshot_time,
)
)
def Import(project, database, input_uri_prefix, namespace_ids, collection_ids):
"""Performs a Firestore Admin v1 Import.
Args:
project: the project id to import, a string.
database: the databae id to import, a string.
input_uri_prefix: the input uri prefix of the exported files, a string.
namespace_ids: a string list of namespace ids to import.
collection_ids: a string list of collections to import.
Returns:
an Operation.
"""
dbname = 'projects/{}/databases/{}'.format(project, database)
return _GetDatabaseService().ImportDocuments(
GetImportDocumentsRequest(
database=dbname,
input_uri_prefix=input_uri_prefix,
namespace_ids=namespace_ids,
collection_ids=collection_ids,
)
)

View File

@@ -0,0 +1,107 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Useful commands for interacting with the Cloud Firestore Indexes API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.firestore import api_utils
from googlecloudsdk.generated_clients.apis.firestore.v1 import firestore_v1_client
from googlecloudsdk.generated_clients.apis.firestore.v1 import firestore_v1_messages
def _GetIndexService() -> (
firestore_v1_client.FirestoreV1.ProjectsDatabasesCollectionGroupsIndexesService
):
"""Returns the Firestore Index service for interacting with the Firestore Admin service."""
return api_utils.GetClient().projects_databases_collectionGroups_indexes
def CreateIndex(
project: str,
database: str,
collection_id: str,
index: firestore_v1_messages.GoogleFirestoreAdminV1Index,
) -> firestore_v1_messages.GoogleLongrunningOperation:
"""Performs a Firestore Admin v1 Index Creation.
Args:
project: the project of the database of the index, a string.
database: the database id of the index, a string.
collection_id: the current group of the index, a string.
index: the index to create, a GoogleFirestoreAdminV1Index message.
Returns:
an Operation.
"""
messages = api_utils.GetMessages()
return _GetIndexService().Create(
messages.FirestoreProjectsDatabasesCollectionGroupsIndexesCreateRequest(
parent='projects/{}/databases/{}/collectionGroups/{}'.format(
project, database, collection_id
),
googleFirestoreAdminV1Index=index,
)
)
def ListIndexes(
project: str, database: str
) -> firestore_v1_messages.GoogleFirestoreAdminV1ListIndexesResponse:
"""Performs a Firestore Admin v1 Index list.
Args:
project: the project of the database of the index, a string.
database: the database id of the index, a string.
Returns:
a list of Indexes.
"""
messages = api_utils.GetMessages()
return _GetIndexService().List(
messages.FirestoreProjectsDatabasesCollectionGroupsIndexesListRequest(
parent='projects/{}/databases/{}/collectionGroups/-'.format(
project, database
),
)
)
def DeleteIndex(
project: str, database: str, index_id: str
) -> firestore_v1_messages.GoogleLongrunningOperation:
"""Performs a Firestore Admin v1 Index Deletion.
Args:
project: the project of the database of the index, a string.
database: the database id of the index, a string.
index_id: the index id of the index, a string
Returns:
an Operation.
"""
messages = api_utils.GetMessages()
return _GetIndexService().Delete(
messages.FirestoreProjectsDatabasesCollectionGroupsIndexesDeleteRequest(
name=(
'projects/{}/databases/{}/collectionGroups/-/indexes/{}'.format(
project,
database,
index_id,
)
),
)
)

View File

@@ -0,0 +1,63 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Useful commands for interacting with the Cloud Firestore Locations API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.firestore import api_utils
def _GetLocationService():
"""Returns the Firestore Location service for interacting with the Firestore Location service."""
return api_utils.GetClient().projects_locations
def ListLocations(project):
"""Lists locations available to Google Cloud Firestore.
Args:
project: the project id to list locations, a string.
Returns:
a List of Locations.
"""
return list_pager.YieldFromList(
_GetLocationService(),
api_utils.GetMessages().FirestoreProjectsLocationsListRequest(
name='projects/{}'.format(project)
),
field='locations',
batch_size_attribute='pageSize',
)
def GetLocation(project, location):
"""Gets a location information for Google Cloud Firestore.
Args:
project: the project id to get the location information, a string.
location: the location id to get the location information, a string.
Returns:
a Firestore Location.
"""
return _GetLocationService().Get(
api_utils.GetMessages().FirestoreProjectsLocationsGetRequest(
name='projects/{}/locations/{}'.format(project, location)
)
)

View File

@@ -0,0 +1,112 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Useful commands for interacting with the Cloud Firestore Operations API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.firestore import api_utils
from googlecloudsdk.api_lib.util import waiter
from googlecloudsdk.core import resources
DEFAULT_PAGE_SIZE = 100
def _GetOperationService():
"""Returns the service for interacting with the Operations service."""
return api_utils.GetClient().projects_databases_operations
def ListOperations(project, database, limit=None, operation_filter=None):
"""Lists all of the Firestore operations.
Args:
project: the project to list operations for, a string.
database: the database to list operations for, a string. Defaults to the
default database.
limit: the maximum number of operations to return, an integer. Defaults to
positive infinity if unset.
operation_filter: a filter to apply to operations, a string.
Returns:
a generator of Operations.
"""
list_request = (
api_utils.GetMessages().FirestoreProjectsDatabasesOperationsListRequest(
filter=operation_filter,
name='projects/{0}/databases/{1}'.format(project, database),
)
)
batch_size = limit if limit else DEFAULT_PAGE_SIZE
return list_pager.YieldFromList(
_GetOperationService(),
list_request,
limit=limit,
batch_size=batch_size,
field='operations',
batch_size_attribute='pageSize',
)
def GetOperation(name):
"""Returns the google.longrunning.Operation with the given name."""
return _GetOperationService().Get(
api_utils.GetMessages().FirestoreProjectsDatabasesOperationsGetRequest(
name=name
)
)
def CancelOperation(name):
"""Cancels the Operation with the given name."""
return _GetOperationService().Cancel(
api_utils.GetMessages().FirestoreProjectsDatabasesOperationsCancelRequest(
name=name
)
)
def DeleteOperation(name):
"""Deletes the Operation with the given name."""
return _GetOperationService().Delete(
api_utils.GetMessages().FirestoreProjectsDatabasesOperationsDeleteRequest(
name=name
)
)
def WaitForOperationWithName(operation_name):
"""Waits for the given Operation to complete."""
operation = api_utils.GetMessages().GoogleLongrunningOperation(
name=operation_name
)
return WaitForOperation(operation)
def WaitForOperation(operation):
"""Waits for the given Operation to complete."""
operation_ref = resources.REGISTRY.Parse(
operation.name,
collection='firestore.projects.databases.operations',
api_version=api_utils.FIRESTORE_API_VERSION)
poller = waiter.CloudOperationPollerNoResources(
_GetOperationService(), lambda x: x.RelativeName()
)
return waiter.WaitFor(
poller, operation_ref,
'Waiting for [{0}] to finish'.format(operation_ref.RelativeName()))

View File

@@ -0,0 +1,28 @@
# -*- coding: utf-8 -*- #
# Copyright 2017 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Backend rewrite tool for Cloud Datastore operations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.datastore import rewrite_backend
class OperationsRewriteBackend(rewrite_backend.OperationsRewriteBackend):
_KEY_MAPPING = {'^collectionIds$': 'metadata.collectionIds'}
_KEY_OPERAND_MAPPING = {}

View File

@@ -0,0 +1,194 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Useful commands for interacting with the Cloud Firestore User Creds API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.firestore import api_utils
def _GetUserCredsService():
"""Returns the service to interact with the Firestore User Creds."""
return api_utils.GetClient().projects_databases_userCreds
def CreateUserCreds(
project, database, user_creds
):
"""Creates a user creds.
Args:
project: the project of the database of the user creds, a string.
database: the database id of the user creds, a string.
user_creds: The user-provided id for the user creds.
Returns:
a user creds.
Raises:
InvalidArgumentException: if user_creds is invalid.
"""
messages = api_utils.GetMessages()
return _GetUserCredsService().Create(
messages.FirestoreProjectsDatabasesUserCredsCreateRequest(
parent='projects/{}/databases/{}'.format(
project,
database,
),
userCredsId=user_creds,
)
)
def GetUserCreds(project, database, user_creds):
"""Gets a user creds.
Args:
project: the project of the database of the user creds, a string.
database: the database id of the user creds, a string.
user_creds: the user creds to read, a string.
Returns:
a user creds.
"""
messages = api_utils.GetMessages()
return _GetUserCredsService().Get(
messages.FirestoreProjectsDatabasesUserCredsGetRequest(
name='projects/{}/databases/{}/userCreds/{}'.format(
project,
database,
user_creds,
),
)
)
def ListUserCreds(project, database):
"""Lists user Creds under a database.
Args:
project: the project of the database of the user creds, a string.
database: the database id of the user creds, a string.
Returns:
a list of user Creds.
"""
messages = api_utils.GetMessages()
return list(
_GetUserCredsService()
.List(
messages.FirestoreProjectsDatabasesUserCredsListRequest(
parent='projects/{}/databases/{}'.format(
project,
database,
),
)
)
.userCreds
)
def EnableUserCreds(project, database, user_creds):
"""Enables a user creds.
Args:
project: the project of the database of the user creds, a string.
database: the database id of the user creds, a string.
user_creds: the user creds to enable, a string.
Returns:
a user creds.
"""
messages = api_utils.GetMessages()
return _GetUserCredsService().Enable(
messages.FirestoreProjectsDatabasesUserCredsEnableRequest(
name='projects/{}/databases/{}/userCreds/{}'.format(
project,
database,
user_creds,
),
)
)
def DisableUserCreds(project, database, user_creds):
"""Disables a user creds.
Args:
project: the project of the database of the user creds, a string.
database: the database id of the user creds, a string.
user_creds: the user creds to disable, a string.
Returns:
a user creds.
"""
messages = api_utils.GetMessages()
return _GetUserCredsService().Disable(
messages.FirestoreProjectsDatabasesUserCredsDisableRequest(
name='projects/{}/databases/{}/userCreds/{}'.format(
project,
database,
user_creds,
),
)
)
def ResetUserCreds(project, database, user_creds):
"""Resets a user creds.
Args:
project: the project of the database of the user creds, a string.
database: the database id of the user creds, a string.
user_creds: the user creds to reset, a string.
Returns:
a user creds.
"""
messages = api_utils.GetMessages()
return _GetUserCredsService().ResetPassword(
messages.FirestoreProjectsDatabasesUserCredsResetPasswordRequest(
name='projects/{}/databases/{}/userCreds/{}'.format(
project,
database,
user_creds,
),
)
)
def DeleteUserCreds(project, database, user_creds):
"""Deletes a user creds.
Args:
project: the project of the database of the user creds, a string.
database: the database id of the user creds, a string.
user_creds: the user creds to delete, a string.
Returns:
Empty response message.
"""
messages = api_utils.GetMessages()
return _GetUserCredsService().Delete(
messages.FirestoreProjectsDatabasesUserCredsDeleteRequest(
name='projects/{}/databases/{}/userCreds/{}'.format(
project,
database,
user_creds,
),
)
)