Package: tidbcloudy
Python SDK for TiDB Cloudtidbcloudyis anunofficialPython SDK forTiDB Cloud. If you encounter any problems or have suggestions, feel free to open an issue on the GitHub repositoryOreoxmt/tidbcloudy.Table of contentsIntroductionCompatibility with TiDB Cloud APIEnhancements comparing to original TiDB Cloud APIInstallationUsagePrerequisitesList all resources in your organizationCreate a project and manage your AWS CMEKNew in 1.0.9Create a clusterConnect to TiDBModify a clusterBackup and restorePause or resume your clusterNew in 1.0.0Get monthly bills of your organizationNew in 1.0.8Delete all resourcesRelated projectsIntroductionFor more information about TiDB Cloud API, see TiDB Cloud API Documentation (v1betaandv1beta1).TiDB Cloud is a fully-managed Database-as-a-Service (DBaaS) that brings everything great about TiDB to your cloud.If you do not have a TiDB Cloud account yet, you can sign uphere. For more details about TiDB Cloud, refer toTiDB Cloud Documentation.You can use this SDK to accessTiDB Cloudand manage your billings, projects, clusters, backups and restores:manage yourbillingsof your organization (get)manage your TiDB Cloudprojects(list,create) and manage theAWS CMEKof your projects (get,create)list all available cloud providers (AWS and GCP), regions, and specifications before creating or modifying a clustermanage your TiDB Serverless or TiDB Dedicatedclusters(create,modify,pause,resume,get,list,delete)manage yourbackupsof a cluster (create,get,list,delete)manage yourrestoresof a project (create,get,list)Compatibility with TiDB Cloud APItidbcloudyis compatible with TiDB Cloud API.Endpoints added inv1beta Release 20230228andv1beta Release 20230905are not supported for now. The following table lists the compatibility betweentidbcloudyand TiDB Cloud API.TiDB Cloud API v1beta1TiDB Cloud API v1beta2023-09-28202309052023080120230602202303282023032120230228202302142023010420221028202209202022090620220823202208091.1.1✅❌✅✅✅✅❌✅✅✅✅✅✅✅1.1.0✅❌✅✅✅✅❌✅✅✅✅✅✅✅1.0.10✅❌✅✅✅✅❌✅✅✅✅✅✅✅1.0.9✅❌✅✅✅✅❌✅✅✅✅✅✅✅1.0.8✅❌✅✅❌✅❌✅✅✅✅✅✅✅1.0.7❌❌✅✅❌✅❌✅✅✅✅✅✅✅1.0.6❌❌✅✅❌✅❌✅✅✅✅✅✅✅1.0.5❌❌✅✅❌✅❌✅✅✅✅✅✅✅1.0.4////❌✅❌✅✅✅✅✅✅✅1.0.3/////////✅✅✅✅✅1.0.2/////////✅✅✅✅✅1.0.1///////////✅✅✅1.0.0////////////✅✅0.2.2/////////////✅0.2.1/////////////✅0.2.0/////////////✅Enhancements comparing to originalTiDB Cloud APIIterate overresources instead of manual paginationConnect to a TiDB clusterusing theMySQL clientGeta Project using a ProjectIDConfigure your cluster withmethod chainingAdd yourcurrent IP address automaticallyWait for the cluster to be readywhen creating/modifying a clusterCase-insensitivewhen setting cluster type, cloud provider, and component nameInstallationpip3installtidbcloudy⚠️ Make sure that you have installedmysql clientin your environment. For more information, seePyMySQL/mysqlclient.UsagePrerequisitesCreate a TiDB Cloud account.Create a TiDB Cloud API key. To manage your API keys, seeTiDB Cloud API Documentation.Install the latest version oftidbcloudy.To get full code examples, see theexamplesfolder.Note:It is recommended to set environment variables for your API public and private key. For example, in bash, you can:exportPUBLIC_KEY=your_api_public_keyexportPRIVATE_KEY=your_api_private_keyList all resources in your organizationThis feature is available intidbcloudy1.0.9 or later.To get the full code example of listing all projects, clusters, backup tasks, and restore tasks in your organization, see0_list_resources.py.importosimporttidbcloudyfromtidbcloudy.specificationimportClusterTypepublic_key=os.environ.get("PUBLIC_KEY")private_key=os.environ.get("PRIVATE_KEY")api=tidbcloudy.TiDBCloud(public_key=public_key,private_key=private_key)forprojectinapi.iter_projects():print(project)ifproject.aws_cmek_enabled:foraws_cmekinproject.iter_aws_cmek():print(aws_cmek)forclusterinproject.iter_clusters():print(cluster)ifcluster.cluster_type==ClusterType.DEDICATED:forbackupincluster.iter_backups():print(backup)forrestoreinproject.iter_restores():print(restore)Create a project and manage your AWS CMEKTo create a project, run the8_manage_project.py.importosimporttidbcloudypublic_key=os.environ.get("PUBLIC_KEY")private_key=os.environ.get("PRIVATE_KEY")debug_mode=os.environ.get("TIDBCLOUDY_LOG")api=tidbcloudy.TiDBCloud(public_key=public_key,private_key=private_key)# Create a project with AWS CMEK enabledproject=api.create_project(name="0",aws_cmek_enabled=True,update_from_server=True)print(project)# Configure AWS CMEK for the projectproject.create_aws_cmek([("your_aws_region_1","your_aws_kms_arn_1"),("your_aws_region_2","your_aws_kms_arn_2")])# List all AWS CMEKs of the projectforcmekinproject.iter_aws_cmek():print(cmek)Create a clusterBefore creating a cluster, you should list all available provider regions and cluster configuration specifications. For more details, run the1_list_provider_regions.py.importosimporttidbcloudypublic_key=os.environ.get("PUBLIC_KEY")private_key=os.environ.get("PRIVATE_KEY")api=tidbcloudy.TiDBCloud(public_key=public_key,private_key=private_key)forspecinapi.list_provider_regions():print(f"- type:{spec.cluster_type.value}")print(f"  provider:{spec.cloud_provider.value}")print(f"  region:{spec.region}")print(f"  components:")fortidbinspec.tidb:print(f"  - tidb:{tidb.node_size}; "f"min={tidb.node_quantity_range.min}step={tidb.node_quantity_range.step}")fortikvinspec.tikv:print(f"  - tikv:{tikv.node_size}; "f"min={tikv.node_quantity_range.min}"f"step={tikv.node_quantity_range.step}; "f"{tikv.storage_size_gib_range.min}..{tikv.storage_size_gib_range.max}GiB")fortiflashinspec.tiflash:print(f"  - tiflash:{tiflash.node_size}; "f"min={tiflash.node_quantity_range.min}step={tiflash.node_quantity_range.step}; "f"{tiflash.storage_size_gib_range.min}..{tiflash.storage_size_gib_range.max}GiB")Note:Creating a cluster might cost money. For more details, seeTiDB Cloud pricing details.To create a TiDB Serverless cluster, run the2_1_create_serverless_cluster.py.To create a TiDB Dedicated cluster, run the2_2_create_dedicated_cluster.py.The following takes creating a TiDB Serverless cluster as an example:importosimporttidbcloudyfromtidbcloudy.specificationimportCreateClusterConfigpublic_key=os.environ.get("PUBLIC_KEY")private_key=os.environ.get("PRIVATE_KEY")debug_mode=os.environ.get("TIDBCLOUDY_LOG")project_id=os.environ.get("PROJECT_ID","1234567890123456789")api=tidbcloudy.TiDBCloud(public_key=public_key,private_key=private_key)project=api.get_project(project_id,update_from_server=True)config=CreateClusterConfig()config\.set_name("serverless-0")\.set_cluster_type("DEVELOPER")\.set_cloud_provider("AWS")\.set_region("us-west-2")\.set_root_password("your_root_password")cluster=project.create_cluster(config)print(cluster)cluster.wait_for_available(interval_sec=1)print(cluster)Connect to TiDBTo connect to your TiDB cluster, run the3_connect_mysql.py.importosimporttidbcloudyfromtidbcloudy.specificationimportClusterStatuspublic_key=os.environ.get("PUBLIC_KEY")private_key=os.environ.get("PRIVATE_KEY")project_id=os.environ.get("PROJECT_ID","1234567890123456789")cluster_id=os.environ.get("CLUSTER_ID","1234567890123456789")print("Connecting to TiDB Cloud...")api=tidbcloudy.TiDBCloud(public_key=public_key,private_key=private_key)project=api.get_project(project_id,update_from_server=True)cluster=project.get_cluster(cluster_id)print(cluster)ifcluster.status.cluster_status==ClusterStatus.AVAILABLE:connection_strings=cluster.status.connection_stringsconnection=cluster.connect(type="standard",database="test",password=os.environ.get("CLUSTER_PWD","your_root_password"))print(connection)withconnection:withconnection.cursor()ascursor:cursor.execute("SELECT DATABASE();")m=cursor.fetchone()print(m[0])Modify a clusterNote:Modify a cluster might cost money. For more details, seeTiDB Cloud pricing details.To modify a cluster, run the4_scale_a_cluster.py.importosimporttidbcloudyfromtidbcloudy.specificationimportUpdateClusterConfigpublic_key=os.environ.get("PUBLIC_KEY")private_key=os.environ.get("PRIVATE_KEY")project_id=os.environ.get("PROJECT_ID","1234567890123456789")cluster_id=os.environ.get("CLUSTER_ID","1234567890123456789")api=tidbcloudy.TiDBCloud(public_key=public_key,private_key=private_key)project=api.get_project(project_id,update_from_server=True)cluster=project.get_cluster(cluster_id)print("The original config is:{}".format(cluster.config.components.to_object()))new_config=UpdateClusterConfig()new_config.update_component("tiflash",node_quantity=1,node_size="8C64G",storage_size_gib=500)cluster.update(new_config)cluster.wait_for_available()print("The new config is:{}".format(cluster.config.components.to_object()))Backup and restoreNote:Backup or restore a cluster might cost money. For more details, seeTiDB Cloud pricing details.To create a backup and restore, run the5_backup_restore.pyimportosimporttidbcloudyfromtidbcloudy.specificationimportCreateClusterConfigpublic_key=os.environ.get("PUBLIC_KEY")private_key=os.environ.get("PRIVATE_KEY")project_id=os.environ.get("PROJECT_ID","1234567890123456789")cluster_id=os.environ.get("CLUSTER_ID","1234567890123456789")backup_id="1234567"api=tidbcloudy.TiDBCloud(public_key=public_key,private_key=private_key)project=api.get_project(project_id,update_from_server=True)cluster=project.get_cluster(cluster_id)print("Create a manual backup task")backup=cluster.create_backup(name="backup-1",description="automatically generated by tidbcloudy")print(backup)config=CreateClusterConfig()config\.set_cluster_type("DEDICATED")\.set_cloud_provider("AWS")\.set_region("us-west-2")\.set_port(4399)\.set_root_password("your_root_password")\.set_component("tidb","8C16G",1)\.set_component("tikv","8C32G",3,500)\.set_component("tiflash","8C64G",1,500)\.add_current_ip_access()print("Create a restore task from backup_id={}".format(backup_id))restore=project.create_restore(backup_id=backup_id,name="restore-1",cluster_config=config)restore_task=project.get_restore(restore.id)print(restore_task.to_object())forrestoreinproject.iter_restores():print(restore)Pause or resume your clusterThis feature is available intidbcloudy1.0.0 or later.To pause or resume your cluster, run the6_pause_cluster.py.importosimporttidbcloudyfromtidbcloudy.specificationimportClusterStatuspublic_key=os.environ.get("PUBLIC_KEY")private_key=os.environ.get("PRIVATE_KEY")project_id=os.environ.get("PROJECT_ID","1234567890123456789")cluster_id=os.environ.get("CLUSTER_ID","1234567890123456789")api=tidbcloudy.TiDBCloud(public_key=public_key,private_key=private_key)project=api.get_project(project_id,update_from_server=True)cluster=project.get_cluster(cluster_id)ifcluster.status.cluster_status==ClusterStatus.AVAILABLE:print("Pause the cluster id={}".format(cluster_id))cluster.pause()ifcluster.status.cluster_status==ClusterStatus.PAUSED:print("Resume the cluster id={}".format(cluster_id))cluster.resume()ifcluster.status.cluster_status==ClusterStatus.RESUMING:print("Wait for the RESUMING cluster id={}to be available".format(cluster_id))cluster.wait_for_available()Get monthly bills of your organizationThis feature is available intidbcloudy1.0.8 or later.To get the billing information of your organization, run thev1beta1_get_monthly_bill.py.importosimporttidbcloudypublic_key=os.environ.get("PUBLIC_KEY")private_key=os.environ.get("PRIVATE_KEY")debug_mode=os.environ.get("TIDBCLOUDY_LOG")api=tidbcloudy.TiDBCloud(public_key=public_key,private_key=private_key)billing=api.get_monthly_bill(month="2023-10")# billing = api.get_monthly_bill(month="202310")# billing = api.get_current_month_bill()print(billing)print(billing.overview)print(billing.summaryByProject)print(billing.summaryByService)Delete all resourcesWarning:This is a destructive operation. It will delete all resources in the project.DO NOTrun this script in a production environment.To delete all clusters and backup tasks in your project, run the7_delete_resources.py.importosimporttidbcloudyfromtidbcloudy.specificationimportClusterTypepublic_key=os.environ.get("PUBLIC_KEY")private_key=os.environ.get("PRIVATE_KEY")project_id=os.environ.get("PROJECT_ID","1234567890123456789")api=tidbcloudy.TiDBCloud(public_key=public_key,private_key=private_key)project=api.get_project(project_id,update_from_server=True)forclusterinproject.iter_clusters():print(cluster)ifcluster.cluster_type==ClusterType.DEDICATED:forbackupincluster.iter_backups():print(backup)backup.delete()cluster.delete()Related projectsGo SDK:go-tidbcloud-sdk-v1by@c4pt0rOfficial TiDB Cloud CLI:tidbcloud-cli|User documentationOfficial code samples in Go and Python:tidbcloud-api-samples