/*
* Документация публичного API
*
* # Введение API Timeweb Cloud позволяет вам управлять ресурсами в облаке программным способом с использованием обычных HTTP-запросов. Множество функций, которые доступны в панели управления Timeweb Cloud, также доступны через API, что позволяет вам автоматизировать ваши собственные сценарии. В этой документации сперва будет описан общий дизайн и принципы работы API, а после этого конкретные конечные точки. Также будут приведены примеры запросов к ним. ## Запросы Запросы должны выполняться по протоколу `HTTPS`, чтобы гарантировать шифрование транзакций. Поддерживаются следующие методы запроса: |Метод|Применение| |--- |--- | |GET|Извлекает данные о коллекциях и отдельных ресурсах.| |POST|Для коллекций создает новый ресурс этого типа. Также используется для выполнения действий с конкретным ресурсом.| |PUT|Обновляет существующий ресурс.| |PATCH|Некоторые ресурсы поддерживают частичное обновление, то есть обновление только части атрибутов ресурса, в этом случае вместо метода PUT будет использован PATCH.| |DELETE|Удаляет ресурс.| Методы `POST`, `PUT` и `PATCH` могут включать объект в тело запроса с типом содержимого `application/json`. ### Параметры в запросах Некоторые коллекции поддерживают пагинацию, поиск или сортировку в запросах. В параметрах запроса требуется передать: - `limit` — обозначает количество записей, которое необходимо вернуть - `offset` — указывает на смещение, относительно начала списка - `search` — позволяет указать набор символов для поиска - `sort` — можно задать правило сортировки коллекции ## Ответы Запросы вернут один из следующих кодов состояния ответа HTTP: |Статус|Описание| |--- |--- | |200 OK|Действие с ресурсом было выполнено успешно.| |201 Created|Ресурс был успешно создан. При этом ресурс может быть как уже готовым к использованию, так и находиться в процессе запуска.| |204 No Content|Действие с ресурсом было выполнено успешно, и ответ не содержит дополнительной информации в теле.| |400 Bad Request|Был отправлен неверный запрос, например, в нем отсутствуют обязательные параметры и т. д. Тело ответа будет содержать дополнительную информацию об ошибке.| |401 Unauthorized|Ошибка аутентификации.| |403 Forbidden|Аутентификация прошла успешно, но недостаточно прав для выполнения действия.| |404 Not Found|Запрашиваемый ресурс не найден.| |409 Conflict|Запрос конфликтует с текущим состоянием.| |423 Locked|Ресурс из запроса заблокирован от применения к нему указанного метода.| |429 Too Many Requests|Был достигнут лимит по количеству запросов в единицу времени.| |500 Internal Server Error|При выполнении запроса произошла какая-то внутренняя ошибка. Чтобы решить эту проблему, лучше всего создать тикет в панели управления.| ### Структура успешного ответа Все конечные точки будут возвращать данные в формате `JSON`. Ответы на `GET`-запросы будут иметь на верхнем уровне следующую структуру атрибутов: |Название поля|Тип|Описание| |--- |--- |--- | |[entity_name]|object, object[], string[], number[], boolean|Динамическое поле, которое будет меняться в зависимости от запрашиваемого ресурса и будет содержать все атрибуты, необходимые для описания этого ресурса. Например, при запросе списка баз данных будет возвращаться поле `dbs`, а при запросе конкретного облачного сервера `server`. Для некоторых конечных точек в ответе может возвращаться сразу несколько ресурсов.| |meta|object|Опционально. Объект, который содержит вспомогательную информацию о ресурсе. Чаще всего будет встречаться при запросе коллекций и содержать поле `total`, которое будет указывать на количество элементов в коллекции.| |response_id|string|Опционально. В большинстве случаев в ответе будет содержаться ID ответа в формате UUIDv4, который однозначно указывает на ваш запрос внутри нашей системы. Если вам потребуется задать вопрос нашей поддержке, приложите к вопросу этот ID— так мы сможем найти ответ на него намного быстрее. Также вы можете использовать этот ID, чтобы убедиться, что это новый ответ на запрос и результат не был получен из кэша.| Пример запроса на получение списка SSH-ключей: ``` HTTP/2.0 200 OK { \"ssh_keys\":[ { \"body\":\"ssh-rsa AAAAB3NzaC1sdfghjkOAsBwWhs= example@device.local\", \"created_at\":\"2021-09-15T19:52:27Z\", \"expired_at\":null, \"id\":5297, \"is_default\":false, \"name\":\"example@device.local\", \"used_at\":null, \"used_by\":[] } ], \"meta\":{ \"total\":1 }, \"response_id\":\"94608d15-8672-4eed-8ab6-28bd6fa3cdf7\" } ``` ### Структура ответа с ошибкой |Название поля|Тип|Описание| |--- |--- |--- | |status_code|number|Короткий числовой идентификатор ошибки.| |error_code|string|Короткий текстовый идентификатор ошибки, который уточняет числовой идентификатор и удобен для программной обработки. Самый простой пример — это код `not_found` для ошибки 404.| |message|string, string[]|Опционально. В большинстве случаев в ответе будет содержаться человекочитаемое подробное описание ошибки или ошибок, которые помогут понять, что нужно исправить.| |response_id|string|Опционально. В большинстве случае в ответе будет содержаться ID ответа в формате UUIDv4, который однозначно указывает на ваш запрос внутри нашей системы. Если вам потребуется задать вопрос нашей поддержке, приложите к вопросу этот ID — так мы сможем найти ответ на него намного быстрее.| Пример: ``` HTTP/2.0 403 Forbidden { \"status_code\": 403, \"error_code\": \"forbidden\", \"message\": \"You do not have access for the attempted action\", \"response_id\": \"94608d15-8672-4eed-8ab6-28bd6fa3cdf7\" } ``` ## Статусы ресурсов Важно учесть, что при создании большинства ресурсов внутри платформы вам будет сразу возвращен ответ от сервера со статусом `200 OK` или `201 Created` и ID созданного ресурса в теле ответа, но при этом этот ресурс может быть ещё в *состоянии запуска*. Для того чтобы понять, в каком состоянии сейчас находится ваш ресурс, мы добавили поле `status` в ответ на получение информации о ресурсе. Список статусов будет отличаться в зависимости от типа ресурса. Увидеть поддерживаемый список статусов вы сможете в описании каждого конкретного ресурса. ## Ограничение скорости запросов (Rate Limiting) Чтобы обеспечить стабильность для всех пользователей, Timeweb Cloud защищает API от всплесков входящего трафика, анализируя количество запросов c каждого аккаунта к каждой конечной точке. Если ваше приложение отправляет более 20 запросов в секунду на одну конечную точку, то для этого запроса API может вернуть код состояния HTTP `429 Too Many Requests`. ## Аутентификация Доступ к API осуществляется с помощью JWT-токена. Токенами можно управлять внутри панели управления Timeweb Cloud в разделе *API и Terraform*. Токен необходимо передавать в заголовке каждого запроса в формате: ``` Authorization: Bearer $TIMEWEB_CLOUD_TOKEN ``` ## Формат примеров API Примеры в этой документации описаны с помощью `curl`, HTTP-клиента командной строки. На компьютерах `Linux` и `macOS` обычно по умолчанию установлен `curl`, и он доступен для загрузки на всех популярных платформах, включая `Windows`. Каждый пример разделен на несколько строк символом `\\`, который совместим с `bash`. Типичный пример выглядит так: ``` curl -X PATCH -H \"Content-Type: application/json\" -H \"Authorization: Bearer $TIMEWEB_CLOUD_TOKEN\" -d '{\"name\":\"Cute Corvus\",\"comment\":\"Development Server\"}' \"https://api.timeweb.cloud/api/v1/dedicated/1051\" ``` - Параметр `-X` задает метод запроса. Для согласованности метод будет указан во всех примерах, даже если он явно не требуется для методов `GET`. - Строки `-H` задают требуемые HTTP-заголовки. - Примеры, для которых требуется объект JSON в теле запроса, передают требуемые данные через параметр `-d`. Чтобы использовать приведенные примеры, не подставляя каждый раз в них свой токен, вы можете добавить токен один раз в переменные окружения в вашей консоли. Например, на `Linux` это можно сделать с помощью команды: ``` TIMEWEB_CLOUD_TOKEN=\"token\" ``` После этого токен будет автоматически подставляться в ваши запросы. Обратите внимание, что все значения в этой документации являются примерами. Не полагайтесь на IDы операционных систем, тарифов и т.д., используемые в примерах. Используйте соответствующую конечную точку для получения значений перед созданием ресурсов. ## Версионирование API построено согласно принципам [семантического версионирования](https://semver.org/lang/ru). Это значит, что мы гарантируем обратную совместимость всех изменений в пределах одной мажорной версии. Мажорная версия каждой конечной точки обозначается в пути запроса, например, запрос `/api/v1/servers` указывает, что этот метод имеет версию 1.
*
* The version of the OpenAPI document: 1.0.0
* Contact: info@timeweb.cloud
* Generated by: https://openapi-generator.tech
*/
use reqwest;
use serde::{Deserialize, Serialize, de::Error as _};
use super::{ContentType, Error, configuration};
use crate::{apis::ResponseContent, models};
/// struct for typed errors of method [`create_database_backup`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateDatabaseBackupError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status409(models::UpdateDatabaseInstance409Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`create_database_backup_download_url`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateDatabaseBackupDownloadUrlError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status409(models::UpdateDatabaseInstance409Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`create_database_cluster`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateDatabaseClusterError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`create_database_instance`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateDatabaseInstanceError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`create_database_s3_backup`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateDatabaseS3BackupError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status409(models::UpdateDatabaseInstance409Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`create_database_user`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateDatabaseUserError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`delete_database_backup`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DeleteDatabaseBackupError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status409(models::UpdateDatabaseInstance409Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`delete_database_cluster`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DeleteDatabaseClusterError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`delete_database_instance`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DeleteDatabaseInstanceError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`delete_database_s3_backup`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DeleteDatabaseS3BackupError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status409(models::UpdateDatabaseInstance409Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`delete_database_user`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DeleteDatabaseUserError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`get_database_auto_backups_settings`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetDatabaseAutoBackupsSettingsError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status409(models::UpdateDatabaseInstance409Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`get_database_backup`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetDatabaseBackupError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status409(models::UpdateDatabaseInstance409Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`get_database_backups`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetDatabaseBackupsError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`get_database_cluster`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetDatabaseClusterError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`get_database_cluster_replicas`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetDatabaseClusterReplicasError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`get_database_cluster_types`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetDatabaseClusterTypesError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`get_database_clusters`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetDatabaseClustersError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`get_database_configurators`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetDatabaseConfiguratorsError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`get_database_default_parameters`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetDatabaseDefaultParametersError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`get_database_instance`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetDatabaseInstanceError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`get_database_instances`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetDatabaseInstancesError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`get_database_parameters`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetDatabaseParametersError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`get_database_preset`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetDatabasePresetError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`get_database_privileges`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetDatabasePrivilegesError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`get_database_s3_backup`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetDatabaseS3BackupError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`get_database_s3_backups`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetDatabaseS3BackupsError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`get_database_user`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetDatabaseUserError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`get_database_users`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetDatabaseUsersError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`get_databases_presets`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetDatabasesPresetsError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`perform_database_cluster_action`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PerformDatabaseClusterActionError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`restore_database_from_backup`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RestoreDatabaseFromBackupError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status409(models::UpdateDatabaseInstance409Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`restore_database_from_s3_backup`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RestoreDatabaseFromS3BackupError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status409(models::UpdateDatabaseInstance409Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`update_database_auto_backups_settings`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UpdateDatabaseAutoBackupsSettingsError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status409(models::UpdateDatabaseInstance409Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`update_database_backup`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UpdateDatabaseBackupError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status409(models::UpdateDatabaseInstance409Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`update_database_cluster`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UpdateDatabaseClusterError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`update_database_cluster_v2`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UpdateDatabaseClusterV2Error {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`update_database_instance`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UpdateDatabaseInstanceError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status409(models::UpdateDatabaseInstance409Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`update_database_s3_backup`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UpdateDatabaseS3BackupError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status409(models::UpdateDatabaseInstance409Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// struct for typed errors of method [`update_database_user`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UpdateDatabaseUserError {
Status400(models::GetFinances400Response),
Status401(models::GetFinances401Response),
Status403(models::GetAccountStatus403Response),
Status404(models::GetImage404Response),
Status429(models::GetFinances429Response),
Status500(models::GetFinances500Response),
UnknownValue(serde_json::Value)
}
/// Чтобы создать бэкап базы данных, отправьте запрос POST в
/// `api/v1/dbs/{db_id}/backups`.
pub async fn create_database_backup(
configuration: &configuration::Configuration,
db_id: i32,
dbs_create_backup: Option<models::DbsCreateBackup>
) -> Result<models::CreateDatabaseBackup201Response, Error<CreateDatabaseBackupError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_id = db_id;
let p_body_dbs_create_backup = dbs_create_backup;
let uri_str = format!(
"{}/api/v1/dbs/{db_id}/backups",
configuration.base_path,
db_id = p_path_db_id
);
let mut req_builder = configuration
.client
.request(reqwest::Method::POST, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
req_builder = req_builder.json(&p_body_dbs_create_backup);
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::CreateDatabaseBackup201Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::CreateDatabaseBackup201Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<CreateDatabaseBackupError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить ссылку для скачивания резервной копии базы данных, отправьте
/// POST-запрос на `/api/v1/dbs/{db_id}/backups/{backup_id}/download-url`.
/// Скачивание резервных копий доступно не для всех кластеров. Если для вашего
/// кластера оно недоступно, метод вернет ошибку со статусом `400`. Тело
/// ответа будет представлять собой объект JSON с ключом `backup_url`.
pub async fn create_database_backup_download_url(
configuration: &configuration::Configuration,
db_id: i32,
backup_id: i32,
backup_download_url_request: models::BackupDownloadUrlRequest
) -> Result<
models::CreateDatabaseBackupDownloadUrl201Response,
Error<CreateDatabaseBackupDownloadUrlError>
> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_id = db_id;
let p_path_backup_id = backup_id;
let p_body_backup_download_url_request = backup_download_url_request;
let uri_str = format!(
"{}/api/v1/dbs/{db_id}/backups/{backup_id}/download-url",
configuration.base_path,
db_id = p_path_db_id,
backup_id = p_path_backup_id
);
let mut req_builder = configuration
.client
.request(reqwest::Method::POST, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
req_builder = req_builder.json(&p_body_backup_download_url_request);
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::CreateDatabaseBackupDownloadUrl201Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::CreateDatabaseBackupDownloadUrl201Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<CreateDatabaseBackupDownloadUrlError> =
serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы создать кластер базы данных на вашем аккаунте, отправьте POST-запрос
/// на `/api/v1/databases`. Вместе с кластером будет создан один инстанс базы
/// данных и один пользователь. Размер кластера задается либо тарифом
/// (`preset_id`), либо конфигуратором (`configuration`). Эти поля
/// взаимоисключающие, но одно из них передать обязательно — запрос без обоих
/// вернется с ошибкой.
pub async fn create_database_cluster(
configuration: &configuration::Configuration,
create_cluster: models::CreateCluster
) -> Result<models::CreateDatabaseCluster201Response, Error<CreateDatabaseClusterError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_body_create_cluster = create_cluster;
let uri_str = format!("{}/api/v1/databases", configuration.base_path);
let mut req_builder = configuration
.client
.request(reqwest::Method::POST, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
req_builder = req_builder.json(&p_body_create_cluster);
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::CreateDatabaseCluster201Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::CreateDatabaseCluster201Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<CreateDatabaseClusterError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы создать инстанс базы данных, отправьте POST-запрос на
/// `/api/v1/databases/{db_cluster_id}/instances`.\\ Существующие
/// пользователи не будут иметь доступа к новой базе данных после создания. Вы
/// можете изменить привилегии для пользователя через <a
/// href='#tag/Bazy-dannyh/operation/updateDatabaseUser'>метод изменения
/// пользователя</a>
pub async fn create_database_instance(
configuration: &configuration::Configuration,
db_cluster_id: i32,
create_instance: models::CreateInstance
) -> Result<models::CreateDatabaseInstance201Response, Error<CreateDatabaseInstanceError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_cluster_id = db_cluster_id;
let p_body_create_instance = create_instance;
let uri_str = format!(
"{}/api/v1/databases/{db_cluster_id}/instances",
configuration.base_path,
db_cluster_id = p_path_db_cluster_id
);
let mut req_builder = configuration
.client
.request(reqwest::Method::POST, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
req_builder = req_builder.json(&p_body_create_instance);
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::CreateDatabaseInstance201Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::CreateDatabaseInstance201Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<CreateDatabaseInstanceError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы создать резервную копию кластера базы данных в объектном хранилище,
/// отправьте POST-запрос на `/api/v2/databases/{db_id}/backups`. Тело запроса
/// необязательно: единственное поле `comment` можно не передавать. Тело ответа
/// будет представлять собой объект JSON с ключом `backup`. Копия создается
/// асинхронно. Пока она создается, ее статус — `running`, и восстановиться из
/// нее нельзя. Дождитесь статуса `success`, опрашивая
/// `/api/v2/databases/{db_id}/backups/{backup_id}`.
pub async fn create_database_s3_backup(
configuration: &configuration::Configuration,
db_id: i32,
create_s3_backup: Option<models::CreateS3Backup>
) -> Result<models::CreateDatabaseS3Backup201Response, Error<CreateDatabaseS3BackupError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_id = db_id;
let p_body_create_s3_backup = create_s3_backup;
let uri_str = format!(
"{}/api/v2/databases/{db_id}/backups",
configuration.base_path,
db_id = p_path_db_id
);
let mut req_builder = configuration
.client
.request(reqwest::Method::POST, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
req_builder = req_builder.json(&p_body_create_s3_backup);
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::CreateDatabaseS3Backup201Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::CreateDatabaseS3Backup201Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<CreateDatabaseS3BackupError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы создать пользователя базы данных, отправьте POST-запрос на
/// `/api/v1/databases/{db_cluster_id}/admins`.
pub async fn create_database_user(
configuration: &configuration::Configuration,
db_cluster_id: i32,
create_admin: models::CreateAdmin
) -> Result<models::CreateDatabaseUser201Response, Error<CreateDatabaseUserError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_cluster_id = db_cluster_id;
let p_body_create_admin = create_admin;
let uri_str = format!(
"{}/api/v1/databases/{db_cluster_id}/admins",
configuration.base_path,
db_cluster_id = p_path_db_cluster_id
);
let mut req_builder = configuration
.client
.request(reqwest::Method::POST, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
req_builder = req_builder.json(&p_body_create_admin);
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::CreateDatabaseUser201Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::CreateDatabaseUser201Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<CreateDatabaseUserError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы удалить бэкап базы данных, отправьте запрос DELETE в
/// `api/v1/dbs/{db_id}/backups/{backup_id}`.
pub async fn delete_database_backup(
configuration: &configuration::Configuration,
db_id: i32,
backup_id: i32
) -> Result<(), Error<DeleteDatabaseBackupError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_id = db_id;
let p_path_backup_id = backup_id;
let uri_str = format!(
"{}/api/v1/dbs/{db_id}/backups/{backup_id}",
configuration.base_path,
db_id = p_path_db_id,
backup_id = p_path_backup_id
);
let mut req_builder = configuration
.client
.request(reqwest::Method::DELETE, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
if !status.is_client_error() && !status.is_server_error() {
Ok(())
} else {
let content = resp.text().await?;
let entity: Option<DeleteDatabaseBackupError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы удалить кластер базы данных, отправьте DELETE-запрос на
/// `/api/v1/databases/{db_cluster_id}`.
pub async fn delete_database_cluster(
configuration: &configuration::Configuration,
db_cluster_id: i32
) -> Result<models::DeleteDatabaseCluster200Response, Error<DeleteDatabaseClusterError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_cluster_id = db_cluster_id;
let uri_str = format!(
"{}/api/v1/databases/{db_cluster_id}",
configuration.base_path,
db_cluster_id = p_path_db_cluster_id
);
let mut req_builder = configuration
.client
.request(reqwest::Method::DELETE, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::DeleteDatabaseCluster200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::DeleteDatabaseCluster200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<DeleteDatabaseClusterError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы удалить инстанс базы данных, отправьте DELETE-запрос на
/// `/api/v1/databases/{db_cluster_id}/instances/{instance_id}`.
pub async fn delete_database_instance(
configuration: &configuration::Configuration,
db_cluster_id: i32,
instance_id: i32
) -> Result<(), Error<DeleteDatabaseInstanceError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_cluster_id = db_cluster_id;
let p_path_instance_id = instance_id;
let uri_str = format!(
"{}/api/v1/databases/{db_cluster_id}/instances/{instance_id}",
configuration.base_path,
db_cluster_id = p_path_db_cluster_id,
instance_id = p_path_instance_id
);
let mut req_builder = configuration
.client
.request(reqwest::Method::DELETE, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
if !status.is_client_error() && !status.is_server_error() {
Ok(())
} else {
let content = resp.text().await?;
let entity: Option<DeleteDatabaseInstanceError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы удалить резервную копию кластера базы данных из объектного хранилища,
/// отправьте DELETE-запрос на `/api/v2/databases/{db_id}/backups/{backup_id}`.
/// Копия удаляется безвозвратно, тело ответа пустое. На резервные копии из
/// `/api/v1/dbs/{db_id}/backups/{backup_id}` этот метод не действует — они
/// удаляются отдельным запросом.
pub async fn delete_database_s3_backup(
configuration: &configuration::Configuration,
db_id: i32,
backup_id: &str
) -> Result<(), Error<DeleteDatabaseS3BackupError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_id = db_id;
let p_path_backup_id = backup_id;
let uri_str = format!(
"{}/api/v2/databases/{db_id}/backups/{backup_id}",
configuration.base_path,
db_id = p_path_db_id,
backup_id = crate::apis::urlencode(p_path_backup_id)
);
let mut req_builder = configuration
.client
.request(reqwest::Method::DELETE, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
if !status.is_client_error() && !status.is_server_error() {
Ok(())
} else {
let content = resp.text().await?;
let entity: Option<DeleteDatabaseS3BackupError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы удалить пользователя базы данных на вашем аккаунте, отправьте
/// DELETE-запрос на `/api/v1/databases/{db_cluster_id}/admins/{admin_id}`.
pub async fn delete_database_user(
configuration: &configuration::Configuration,
db_cluster_id: i32,
admin_id: i32
) -> Result<(), Error<DeleteDatabaseUserError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_cluster_id = db_cluster_id;
let p_path_admin_id = admin_id;
let uri_str = format!(
"{}/api/v1/databases/{db_cluster_id}/admins/{admin_id}",
configuration.base_path,
db_cluster_id = p_path_db_cluster_id,
admin_id = p_path_admin_id
);
let mut req_builder = configuration
.client
.request(reqwest::Method::DELETE, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
if !status.is_client_error() && !status.is_server_error() {
Ok(())
} else {
let content = resp.text().await?;
let entity: Option<DeleteDatabaseUserError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить список настроек автобэкапов базы данных, отправьте запрос GET
/// в `api/v1/dbs/{db_id}/auto-backups`
pub async fn get_database_auto_backups_settings(
configuration: &configuration::Configuration,
db_id: i32
) -> Result<
models::GetDatabaseAutoBackupsSettings200Response,
Error<GetDatabaseAutoBackupsSettingsError>
> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_id = db_id;
let uri_str = format!(
"{}/api/v1/dbs/{db_id}/auto-backups",
configuration.base_path,
db_id = p_path_db_id
);
let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::GetDatabaseAutoBackupsSettings200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::GetDatabaseAutoBackupsSettings200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<GetDatabaseAutoBackupsSettingsError> =
serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить бэкап базы данных, отправьте запрос GET в
/// `api/v1/dbs/{db_id}/backups/{backup_id}`.
pub async fn get_database_backup(
configuration: &configuration::Configuration,
db_id: i32,
backup_id: i32
) -> Result<models::GetDatabaseBackup200Response, Error<GetDatabaseBackupError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_id = db_id;
let p_path_backup_id = backup_id;
let uri_str = format!(
"{}/api/v1/dbs/{db_id}/backups/{backup_id}",
configuration.base_path,
db_id = p_path_db_id,
backup_id = p_path_backup_id
);
let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::GetDatabaseBackup200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::GetDatabaseBackup200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<GetDatabaseBackupError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить список бэкапов базы данных, отправьте запрос GET в
/// `api/v1/dbs/{db_id}/backups`.
pub async fn get_database_backups(
configuration: &configuration::Configuration,
db_id: i32,
limit: Option<i32>,
offset: Option<i32>
) -> Result<models::GetDatabaseBackups200Response, Error<GetDatabaseBackupsError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_id = db_id;
let p_query_limit = limit;
let p_query_offset = offset;
let uri_str = format!(
"{}/api/v1/dbs/{db_id}/backups",
configuration.base_path,
db_id = p_path_db_id
);
let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
if let Some(ref param_value) = p_query_limit {
req_builder = req_builder.query(&[("limit", ¶m_value.to_string())]);
}
if let Some(ref param_value) = p_query_offset {
req_builder = req_builder.query(&[("offset", ¶m_value.to_string())]);
}
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::GetDatabaseBackups200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::GetDatabaseBackups200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<GetDatabaseBackupsError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить кластер базы данных на вашем аккаунте, отправьте GET-запрос
/// на `/api/v1/databases/{db_cluster_id}`.
pub async fn get_database_cluster(
configuration: &configuration::Configuration,
db_cluster_id: i32
) -> Result<models::CreateDatabaseCluster201Response, Error<GetDatabaseClusterError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_cluster_id = db_cluster_id;
let uri_str = format!(
"{}/api/v1/databases/{db_cluster_id}",
configuration.base_path,
db_cluster_id = p_path_db_cluster_id
);
let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::CreateDatabaseCluster201Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::CreateDatabaseCluster201Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<GetDatabaseClusterError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить список реплик кластера базы данных, отправьте GET-запрос на
/// `/api/v1/databases/{db_cluster_id}/replicas`. Тело ответа будет
/// представлять собой объект JSON с ключом `replicas`.
pub async fn get_database_cluster_replicas(
configuration: &configuration::Configuration,
db_cluster_id: i32
) -> Result<models::GetDatabaseClusterReplicas200Response, Error<GetDatabaseClusterReplicasError>>
{
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_cluster_id = db_cluster_id;
let uri_str = format!(
"{}/api/v1/databases/{db_cluster_id}/replicas",
configuration.base_path,
db_cluster_id = p_path_db_cluster_id
);
let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::GetDatabaseClusterReplicas200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::GetDatabaseClusterReplicas200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<GetDatabaseClusterReplicasError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить список типов баз данных на вашем аккаунте, отправьте
/// GET-запрос на `/api/v1/database-types`.
pub async fn get_database_cluster_types(
configuration: &configuration::Configuration
) -> Result<models::GetDatabaseClusterTypes200Response, Error<GetDatabaseClusterTypesError>> {
let uri_str = format!("{}/api/v1/database-types", configuration.base_path);
let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::GetDatabaseClusterTypes200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::GetDatabaseClusterTypes200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<GetDatabaseClusterTypesError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить список кластеров баз данных, отправьте GET-запрос на
/// `/api/v1/databases`. Тело ответа будет представлять собой объект JSON с
/// ключом `dbs`.
pub async fn get_database_clusters(
configuration: &configuration::Configuration,
limit: Option<i32>,
offset: Option<i32>
) -> Result<models::GetDatabaseClusters200Response, Error<GetDatabaseClustersError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_query_limit = limit;
let p_query_offset = offset;
let uri_str = format!("{}/api/v1/databases", configuration.base_path);
let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
if let Some(ref param_value) = p_query_limit {
req_builder = req_builder.query(&[("limit", ¶m_value.to_string())]);
}
if let Some(ref param_value) = p_query_offset {
req_builder = req_builder.query(&[("offset", ¶m_value.to_string())]);
}
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::GetDatabaseClusters200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::GetDatabaseClusters200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<GetDatabaseClustersError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить список конфигураторов баз данных, отправьте GET-запрос на
/// `/api/v1/configurator/databases`. Конфигуратор позволяет создать кластер с
/// произвольным количеством ресурсов вместо готового тарифа: его ID передается
/// при создании кластера в поле `configuration.configurator_id`, а допустимые
/// значения ресурсов ограничены объектом `requirements`. Тело ответа будет
/// представлять собой объект JSON с ключом `database_configurators`.
pub async fn get_database_configurators(
configuration: &configuration::Configuration,
cluster_id: Option<i32>,
with_unavailable: Option<bool>
) -> Result<models::GetDatabaseConfigurators200Response, Error<GetDatabaseConfiguratorsError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_query_cluster_id = cluster_id;
let p_query_with_unavailable = with_unavailable;
let uri_str = format!("{}/api/v1/configurator/databases", configuration.base_path);
let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
if let Some(ref param_value) = p_query_cluster_id {
req_builder = req_builder.query(&[("cluster_id", ¶m_value.to_string())]);
}
if let Some(ref param_value) = p_query_with_unavailable {
req_builder = req_builder.query(&[("with_unavailable", ¶m_value.to_string())]);
}
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::GetDatabaseConfigurators200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::GetDatabaseConfigurators200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<GetDatabaseConfiguratorsError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить рекомендуемые значения параметров базы данных, отправьте
/// GET-запрос на `/api/v1/dbs/default-parameters`. Значения рассчитываются
/// для указанного типа кластера, объема оперативной памяти и количества реплик
/// — их можно передать при создании кластера в поле `config_parameters`. Список
/// имен параметров, доступных для каждого типа кластера, возвращает `GET
/// /api/v1/dbs/parameters`. Тело ответа будет представлять собой объект JSON
/// с ключом `config_params`. Рекомендуемые значения рассчитываются только для
/// кластеров MySQL, PostgreSQL и Valkey — для остальных типов возвращается
/// пустой объект.
pub async fn get_database_default_parameters(
configuration: &configuration::Configuration,
r#type: &str,
ram: i32,
replica_count: Option<i32>
) -> Result<
models::GetDatabaseDefaultParameters200Response,
Error<GetDatabaseDefaultParametersError>
> {
// add a prefix to parameters to efficiently prevent name collisions
let p_query_type = r#type;
let p_query_ram = ram;
let p_query_replica_count = replica_count;
let uri_str = format!("{}/api/v1/dbs/default-parameters", configuration.base_path);
let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
req_builder = req_builder.query(&[("type", &p_query_type.to_string())]);
req_builder = req_builder.query(&[("ram", &p_query_ram.to_string())]);
if let Some(ref param_value) = p_query_replica_count {
req_builder = req_builder.query(&[("replica_count", ¶m_value.to_string())]);
}
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::GetDatabaseDefaultParameters200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::GetDatabaseDefaultParameters200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<GetDatabaseDefaultParametersError> =
serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить инстанс базы данных, отправьте GET-запрос на
/// `/api/v1/databases/{db_cluster_id}/instances/{instance_id}`.
pub async fn get_database_instance(
configuration: &configuration::Configuration,
db_cluster_id: i32,
instance_id: i32
) -> Result<models::CreateDatabaseInstance201Response, Error<GetDatabaseInstanceError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_cluster_id = db_cluster_id;
let p_path_instance_id = instance_id;
let uri_str = format!(
"{}/api/v1/databases/{db_cluster_id}/instances/{instance_id}",
configuration.base_path,
db_cluster_id = p_path_db_cluster_id,
instance_id = p_path_instance_id
);
let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::CreateDatabaseInstance201Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::CreateDatabaseInstance201Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<GetDatabaseInstanceError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить список баз данных на вашем аккаунте, отправьте GET-запрос на
/// `/api/v1/databases/{db_cluster_id}/instances`.
pub async fn get_database_instances(
configuration: &configuration::Configuration,
db_cluster_id: i32
) -> Result<models::GetDatabaseInstances200Response, Error<GetDatabaseInstancesError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_cluster_id = db_cluster_id;
let uri_str = format!(
"{}/api/v1/databases/{db_cluster_id}/instances",
configuration.base_path,
db_cluster_id = p_path_db_cluster_id
);
let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::GetDatabaseInstances200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::GetDatabaseInstances200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<GetDatabaseInstancesError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить список параметров баз данных, отправьте GET-запрос на
/// `/api/v1/dbs/parameters`. Ответ содержит только имена параметров,
/// доступных для каждого типа кластера. Рекомендуемые значения этих параметров
/// для конкретной конфигурации возвращает `GET /api/v1/dbs/default-parameters`.
pub async fn get_database_parameters(
configuration: &configuration::Configuration
) -> Result<models::GetDatabaseParameters200Response, Error<GetDatabaseParametersError>> {
let uri_str = format!("{}/api/v1/dbs/parameters", configuration.base_path);
let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::GetDatabaseParameters200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::GetDatabaseParameters200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<GetDatabaseParametersError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить тариф для базы данных, отправьте GET-запрос на
/// `/api/v2/dbs/presets/{preset_id}`. Тело ответа будет представлять собой
/// объект JSON с ключом `databases_preset`.
pub async fn get_database_preset(
configuration: &configuration::Configuration,
preset_id: i32
) -> Result<models::GetDatabasePreset200Response, Error<GetDatabasePresetError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_preset_id = preset_id;
let uri_str = format!(
"{}/api/v2/dbs/presets/{preset_id}",
configuration.base_path,
preset_id = p_path_preset_id
);
let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::GetDatabasePreset200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::GetDatabasePreset200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<GetDatabasePresetError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить список привилегий, которые можно выдать пользователям
/// кластера базы данных, отправьте GET-запрос на
/// `/api/v1/databases/{db_cluster_id}/privileges`.\\ Список зависит от типа
/// СУБД кластера и определяется сервером автоматически: возвращаются только те
/// привилегии, которые допустимы для этого кластера. Используйте его, чтобы
/// заполнить поле `privileges` при <a
/// href='#tag/Bazy-dannyh/operation/createDatabaseUser'>создании</a> или <a
/// href='#tag/Bazy-dannyh/operation/updateDatabaseUser'>изменении</a>
/// пользователя базы данных.
pub async fn get_database_privileges(
configuration: &configuration::Configuration,
db_cluster_id: i32
) -> Result<models::GetDatabasePrivileges200Response, Error<GetDatabasePrivilegesError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_cluster_id = db_cluster_id;
let uri_str = format!(
"{}/api/v1/databases/{db_cluster_id}/privileges",
configuration.base_path,
db_cluster_id = p_path_db_cluster_id
);
let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::GetDatabasePrivileges200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::GetDatabasePrivileges200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<GetDatabasePrivilegesError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить информацию о резервной копии кластера базы данных в объектном
/// хранилище, отправьте GET-запрос на
/// `/api/v2/databases/{db_id}/backups/{backup_id}`. Тело ответа будет
/// представлять собой объект JSON с ключом `backup`. Обратите внимание, что
/// `backup_id` здесь — строка в формате UUID, а не число, как в
/// `/api/v1/dbs/{db_id}/backups/{backup_id}`.
pub async fn get_database_s3_backup(
configuration: &configuration::Configuration,
db_id: i32,
backup_id: &str
) -> Result<models::CreateDatabaseS3Backup201Response, Error<GetDatabaseS3BackupError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_id = db_id;
let p_path_backup_id = backup_id;
let uri_str = format!(
"{}/api/v2/databases/{db_id}/backups/{backup_id}",
configuration.base_path,
db_id = p_path_db_id,
backup_id = crate::apis::urlencode(p_path_backup_id)
);
let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::CreateDatabaseS3Backup201Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::CreateDatabaseS3Backup201Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<GetDatabaseS3BackupError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить список резервных копий кластера базы данных в объектном
/// хранилище, отправьте GET-запрос на `/api/v2/databases/{db_id}/backups`.
/// Тело ответа будет представлять собой объект JSON с ключом `backups`. Копии
/// отсортированы по дате создания по убыванию — сначала самые свежие.
/// Резервное копирование в объектное хранилище доступно для кластеров MySQL и
/// PostgreSQL. Идентификатор такой копии — строка в формате UUID; это отдельный
/// от `/api/v1/dbs/{db_id}/backups` механизм, и идентификаторы копий между ними
/// не взаимозаменяемы.
pub async fn get_database_s3_backups(
configuration: &configuration::Configuration,
db_id: i32
) -> Result<models::GetDatabaseS3Backups200Response, Error<GetDatabaseS3BackupsError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_id = db_id;
let uri_str = format!(
"{}/api/v2/databases/{db_id}/backups",
configuration.base_path,
db_id = p_path_db_id
);
let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::GetDatabaseS3Backups200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::GetDatabaseS3Backups200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<GetDatabaseS3BackupsError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить пользователя базы данных на вашем аккаунте, отправьте
/// GET-запрос на `/api/v1/databases/{db_cluster_id}/admins/{admin_id}`.
pub async fn get_database_user(
configuration: &configuration::Configuration,
db_cluster_id: i32,
admin_id: i32
) -> Result<models::CreateDatabaseUser201Response, Error<GetDatabaseUserError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_cluster_id = db_cluster_id;
let p_path_admin_id = admin_id;
let uri_str = format!(
"{}/api/v1/databases/{db_cluster_id}/admins/{admin_id}",
configuration.base_path,
db_cluster_id = p_path_db_cluster_id,
admin_id = p_path_admin_id
);
let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::CreateDatabaseUser201Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::CreateDatabaseUser201Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<GetDatabaseUserError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить список пользователей базы данных на вашем аккаунте, отправьте
/// GET-запрос на `/api/v1/databases/{db_cluster_id}/admins`.
pub async fn get_database_users(
configuration: &configuration::Configuration,
db_cluster_id: i32
) -> Result<models::GetDatabaseUsers200Response, Error<GetDatabaseUsersError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_cluster_id = db_cluster_id;
let uri_str = format!(
"{}/api/v1/databases/{db_cluster_id}/admins",
configuration.base_path,
db_cluster_id = p_path_db_cluster_id
);
let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::GetDatabaseUsers200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::GetDatabaseUsers200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<GetDatabaseUsersError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы получить список тарифов для баз данных, отправьте GET-запрос на
/// `/api/v2/presets/dbs`. Без параметров возвращаются тарифы, доступные к
/// заказу — этот список используется при создании кластера. Если передать
/// `cluster_id`, вернутся тарифы группы, в пределах которой можно сменить тариф
/// указанного кластера. Тело ответа будет представлять собой объект JSON с
/// ключом `databases_presets`.
pub async fn get_databases_presets(
configuration: &configuration::Configuration,
cluster_id: Option<i32>,
with_unavailable: Option<bool>
) -> Result<models::GetDatabasesPresets200Response, Error<GetDatabasesPresetsError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_query_cluster_id = cluster_id;
let p_query_with_unavailable = with_unavailable;
let uri_str = format!("{}/api/v2/presets/dbs", configuration.base_path);
let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
if let Some(ref param_value) = p_query_cluster_id {
req_builder = req_builder.query(&[("cluster_id", ¶m_value.to_string())]);
}
if let Some(ref param_value) = p_query_with_unavailable {
req_builder = req_builder.query(&[("with_unavailable", ¶m_value.to_string())]);
}
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::GetDatabasesPresets200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::GetDatabasesPresets200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<GetDatabasesPresetsError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы выполнить действие над кластером базы данных, отправьте POST-запрос на
/// `/api/v1/databases/{db_cluster_id}/action`. Доступные действия: `reboot` —
/// перезагрузка кластера, `shutdown` — выключение кластера, `start` — включение
/// кластера.
pub async fn perform_database_cluster_action(
configuration: &configuration::Configuration,
db_cluster_id: i32,
cluster_action: models::ClusterAction
) -> Result<(), Error<PerformDatabaseClusterActionError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_cluster_id = db_cluster_id;
let p_body_cluster_action = cluster_action;
let uri_str = format!(
"{}/api/v1/databases/{db_cluster_id}/action",
configuration.base_path,
db_cluster_id = p_path_db_cluster_id
);
let mut req_builder = configuration
.client
.request(reqwest::Method::POST, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
req_builder = req_builder.json(&p_body_cluster_action);
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
if !status.is_client_error() && !status.is_server_error() {
Ok(())
} else {
let content = resp.text().await?;
let entity: Option<PerformDatabaseClusterActionError> =
serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы восстановить базу данных из бэкапа, отправьте запрос PUT в
/// `api/v1/dbs/{db_id}/backups/{backup_id}`.
pub async fn restore_database_from_backup(
configuration: &configuration::Configuration,
db_id: i32,
backup_id: i32
) -> Result<(), Error<RestoreDatabaseFromBackupError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_id = db_id;
let p_path_backup_id = backup_id;
let uri_str = format!(
"{}/api/v1/dbs/{db_id}/backups/{backup_id}",
configuration.base_path,
db_id = p_path_db_id,
backup_id = p_path_backup_id
);
let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
if !status.is_client_error() && !status.is_server_error() {
Ok(())
} else {
let content = resp.text().await?;
let entity: Option<RestoreDatabaseFromBackupError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы восстановить кластер базы данных из резервной копии в объектном
/// хранилище, отправьте POST-запрос на
/// `/api/v2/databases/{db_id}/backups/{backup_id}/restore`. Тела запроса нет,
/// тело ответа пустое. Восстановиться можно только из копии со статусом
/// `success`. Сразу после запуска кластер переходит в статус
/// `backup_recovery`. Пока восстановление не завершится, создание, изменение и
/// удаление резервных копий, а также повторный запуск восстановления
/// недоступны.
pub async fn restore_database_from_s3_backup(
configuration: &configuration::Configuration,
db_id: i32,
backup_id: &str
) -> Result<(), Error<RestoreDatabaseFromS3BackupError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_id = db_id;
let p_path_backup_id = backup_id;
let uri_str = format!(
"{}/api/v2/databases/{db_id}/backups/{backup_id}/restore",
configuration.base_path,
db_id = p_path_db_id,
backup_id = crate::apis::urlencode(p_path_backup_id)
);
let mut req_builder = configuration
.client
.request(reqwest::Method::POST, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
if !status.is_client_error() && !status.is_server_error() {
Ok(())
} else {
let content = resp.text().await?;
let entity: Option<RestoreDatabaseFromS3BackupError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы изменить список настроек автобэкапов базы данных, отправьте запрос
/// PATCH в `api/v1/dbs/{db_id}/auto-backups`
pub async fn update_database_auto_backups_settings(
configuration: &configuration::Configuration,
db_id: i32,
update_auto_backup: models::UpdateAutoBackup
) -> Result<
models::GetDatabaseAutoBackupsSettings200Response,
Error<UpdateDatabaseAutoBackupsSettingsError>
> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_id = db_id;
let p_body_update_auto_backup = update_auto_backup;
let uri_str = format!(
"{}/api/v1/dbs/{db_id}/auto-backups",
configuration.base_path,
db_id = p_path_db_id
);
let mut req_builder = configuration
.client
.request(reqwest::Method::PATCH, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
req_builder = req_builder.json(&p_body_update_auto_backup);
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::GetDatabaseAutoBackupsSettings200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::GetDatabaseAutoBackupsSettings200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<UpdateDatabaseAutoBackupsSettingsError> =
serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы изменить комментарий к бэкапу базы данных, отправьте PATCH-запрос на
/// `/api/v1/dbs/{db_id}/backups/{backup_id}`. Тело ответа будет представлять
/// собой объект JSON с ключом `backup`.
pub async fn update_database_backup(
configuration: &configuration::Configuration,
db_id: i32,
backup_id: i32,
dbs_update_backup: models::DbsUpdateBackup
) -> Result<models::GetDatabaseBackup200Response, Error<UpdateDatabaseBackupError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_id = db_id;
let p_path_backup_id = backup_id;
let p_body_dbs_update_backup = dbs_update_backup;
let uri_str = format!(
"{}/api/v1/dbs/{db_id}/backups/{backup_id}",
configuration.base_path,
db_id = p_path_db_id,
backup_id = p_path_backup_id
);
let mut req_builder = configuration
.client
.request(reqwest::Method::PATCH, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
req_builder = req_builder.json(&p_body_dbs_update_backup);
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::GetDatabaseBackup200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::GetDatabaseBackup200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<UpdateDatabaseBackupError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы изменить кластер базы данных на вашем аккаунте, отправьте PATCH-запрос
/// на `/api/v1/databases/{db_cluster_id}`. Размер кластера задается либо
/// тарифом (`preset_id`), либо конфигуратором (`configuration`) — эти поля
/// взаимоисключающие.
pub async fn update_database_cluster(
configuration: &configuration::Configuration,
db_cluster_id: i32,
update_cluster: models::UpdateCluster
) -> Result<models::UpdateDatabaseCluster200Response, Error<UpdateDatabaseClusterError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_cluster_id = db_cluster_id;
let p_body_update_cluster = update_cluster;
let uri_str = format!(
"{}/api/v1/databases/{db_cluster_id}",
configuration.base_path,
db_cluster_id = p_path_db_cluster_id
);
let mut req_builder = configuration
.client
.request(reqwest::Method::PATCH, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
req_builder = req_builder.json(&p_body_update_cluster);
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::UpdateDatabaseCluster200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::UpdateDatabaseCluster200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<UpdateDatabaseClusterError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы изменить кластер базы данных на вашем аккаунте, отправьте PATCH-запрос
/// на `/api/v2/databases/{db_cluster_id}`. В отличие от
/// `/api/v1/databases/{db_cluster_id}`, эта версия дополнительно позволяет
/// привязать плавающий IP-адрес (`floating_ip`). Размер кластера задается
/// либо тарифом (`preset_id`), либо конфигуратором (`configuration`) — эти поля
/// взаимоисключающие.
pub async fn update_database_cluster_v2(
configuration: &configuration::Configuration,
db_cluster_id: i32,
update_cluster_v2: models::UpdateClusterV2
) -> Result<models::UpdateDatabaseCluster200Response, Error<UpdateDatabaseClusterV2Error>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_cluster_id = db_cluster_id;
let p_body_update_cluster_v2 = update_cluster_v2;
let uri_str = format!(
"{}/api/v2/databases/{db_cluster_id}",
configuration.base_path,
db_cluster_id = p_path_db_cluster_id
);
let mut req_builder = configuration
.client
.request(reqwest::Method::PATCH, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
req_builder = req_builder.json(&p_body_update_cluster_v2);
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::UpdateDatabaseCluster200Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::UpdateDatabaseCluster200Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<UpdateDatabaseClusterV2Error> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы изменить инстанс базы данных, отправьте PATCH-запрос на
/// `/api/v1/databases/{db_cluster_id}/instances/{instance_id}`. Изменить
/// название базы данных (`name`) и ее владельца (`owner_id`) можно только в
/// кластере PostgreSQL, а настройки топика (`config_parameters`) — только в
/// кластере Kafka. Если один из этих трех параметров передан для неподходящего
/// типа кластера, запрос вернется с ошибкой 409. Расширения (`extensions`)
/// применимы к кластерам PostgreSQL и RabbitMQ.
pub async fn update_database_instance(
configuration: &configuration::Configuration,
db_cluster_id: i32,
instance_id: i32,
update_instance: models::UpdateInstance
) -> Result<models::CreateDatabaseInstance201Response, Error<UpdateDatabaseInstanceError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_cluster_id = db_cluster_id;
let p_path_instance_id = instance_id;
let p_body_update_instance = update_instance;
let uri_str = format!(
"{}/api/v1/databases/{db_cluster_id}/instances/{instance_id}",
configuration.base_path,
db_cluster_id = p_path_db_cluster_id,
instance_id = p_path_instance_id
);
let mut req_builder = configuration
.client
.request(reqwest::Method::PATCH, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
req_builder = req_builder.json(&p_body_update_instance);
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::CreateDatabaseInstance201Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::CreateDatabaseInstance201Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<UpdateDatabaseInstanceError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы изменить комментарий к резервной копии кластера базы данных, отправьте
/// PATCH-запрос на `/api/v2/databases/{db_id}/backups/{backup_id}`. Изменить
/// можно только комментарий: других полей метод не принимает, сама резервная
/// копия при этом не пересоздается. Тело ответа будет представлять собой объект
/// JSON с ключом `backup`.
pub async fn update_database_s3_backup(
configuration: &configuration::Configuration,
db_id: i32,
backup_id: &str,
update_s3_backup: Option<models::UpdateS3Backup>
) -> Result<models::CreateDatabaseS3Backup201Response, Error<UpdateDatabaseS3BackupError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_id = db_id;
let p_path_backup_id = backup_id;
let p_body_update_s3_backup = update_s3_backup;
let uri_str = format!(
"{}/api/v2/databases/{db_id}/backups/{backup_id}",
configuration.base_path,
db_id = p_path_db_id,
backup_id = crate::apis::urlencode(p_path_backup_id)
);
let mut req_builder = configuration
.client
.request(reqwest::Method::PATCH, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
req_builder = req_builder.json(&p_body_update_s3_backup);
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::CreateDatabaseS3Backup201Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::CreateDatabaseS3Backup201Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<UpdateDatabaseS3BackupError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}
/// Чтобы изменить пользователя базы данных на вашем аккаунте, отправьте
/// PATCH-запрос на `/api/v1/databases/{db_cluster_id}/admins/{admin_id}`.
pub async fn update_database_user(
configuration: &configuration::Configuration,
db_cluster_id: i32,
admin_id: i32,
update_admin: models::UpdateAdmin
) -> Result<models::CreateDatabaseUser201Response, Error<UpdateDatabaseUserError>> {
// add a prefix to parameters to efficiently prevent name collisions
let p_path_db_cluster_id = db_cluster_id;
let p_path_admin_id = admin_id;
let p_body_update_admin = update_admin;
let uri_str = format!(
"{}/api/v1/databases/{db_cluster_id}/admins/{admin_id}",
configuration.base_path,
db_cluster_id = p_path_db_cluster_id,
admin_id = p_path_admin_id
);
let mut req_builder = configuration
.client
.request(reqwest::Method::PATCH, &uri_str);
if let Some(ref user_agent) = configuration.user_agent {
req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
}
if let Some(ref token) = configuration.bearer_access_token {
req_builder = req_builder.bearer_auth(token.to_owned());
};
req_builder = req_builder.json(&p_body_update_admin);
let req = req_builder.build()?;
let resp = configuration.client.execute(req).await?;
let status = resp.status();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream");
let content_type = super::ContentType::from(content_type);
if !status.is_client_error() && !status.is_server_error() {
let content = resp.text().await?;
match content_type {
ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
ContentType::Text => {
return Err(Error::from(serde_json::Error::custom(
"Received `text/plain` content type response that cannot be converted to `models::CreateDatabaseUser201Response`"
)));
}
ContentType::Unsupported(unknown_type) => {
return Err(Error::from(serde_json::Error::custom(format!(
"Received `{unknown_type}` content type response that cannot be converted to `models::CreateDatabaseUser201Response`"
))));
}
}
} else {
let content = resp.text().await?;
let entity: Option<UpdateDatabaseUserError> = serde_json::from_str(&content).ok();
Err(Error::ResponseError(ResponseContent {
status,
content,
entity
}))
}
}