Google Cloud SQL Operators

Prerequisite Tasks

CloudSQLCreateInstanceDatabaseOperator

Creates a new database inside a Cloud SQL instance.

For parameter definition, take a look at CloudSQLCreateInstanceDatabaseOperator.

Using the operator

You can create the operator with or without project id. If project id is missing it will be retrieved from the Google Cloud connection used. Both variants are shown:

tests/system/providers/google/cloud/cloud_sql/example_cloud_sql.py[source]

sql_db_create_task = CloudSQLCreateInstanceDatabaseOperator(
    body=db_create_body, instance=INSTANCE_NAME, task_id='sql_db_create_task'
)

Example request body:

tests/system/providers/google/cloud/cloud_sql/example_cloud_sql.py[source]

db_create_body = {"instance": INSTANCE_NAME, "name": DB_NAME, "project": PROJECT_ID}

Templating

template_fields: Sequence[str] = (
    'project_id',
    'instance',
    'body',
    'gcp_conn_id',
    'api_version',
    'impersonation_chain',
)

More information

See Google Cloud SQL API documentation for to create a new database inside the instance.

CloudSQLDeleteInstanceDatabaseOperator

Deletes a database from a Cloud SQL instance.

For parameter definition, take a look at CloudSQLDeleteInstanceDatabaseOperator.

Using the operator

You can create the operator with or without project id. If project id is missing it will be retrieved from the Google Cloud connection used. Both variants are shown:

tests/system/providers/google/cloud/cloud_sql/example_cloud_sql.py[source]

sql_db_delete_task = CloudSQLDeleteInstanceDatabaseOperator(
    instance=INSTANCE_NAME, database=DB_NAME, task_id='sql_db_delete_task'
)

Templating

template_fields: Sequence[str] = (
    'project_id',
    'instance',
    'database',
    'gcp_conn_id',
    'api_version',
    'impersonation_chain',
)

More information

See Google Cloud SQL API documentation to delete a database.

CloudSQLPatchInstanceDatabaseOperator

Updates a resource containing information about a database inside a Cloud SQL instance using patch semantics. See: https://cloud.google.com/sql/docs/mysql/admin-api/how-tos/performance#patch

For parameter definition, take a look at CloudSQLPatchInstanceDatabaseOperator.

Using the operator

You can create the operator with or without project id. If project id is missing it will be retrieved from the Google Cloud connection used. Both variants are shown:

tests/system/providers/google/cloud/cloud_sql/example_cloud_sql.py[source]

sql_db_patch_task = CloudSQLPatchInstanceDatabaseOperator(
    body=db_patch_body,
    instance=INSTANCE_NAME,
    database=DB_NAME,
    task_id='sql_db_patch_task',
)

Example request body:

tests/system/providers/google/cloud/cloud_sql/example_cloud_sql.py[source]

db_patch_body = {"charset": "utf16", "collation": "utf16_general_ci"}

Templating

template_fields: Sequence[str] = (
    'project_id',
    'instance',
    'body',
    'database',
    'gcp_conn_id',
    'api_version',
    'impersonation_chain',
)

More information

See Google Cloud SQL API documentation to update a database.

CloudSQLDeleteInstanceOperator

Deletes a Cloud SQL instance in Google Cloud.

It is also used for deleting read and failover replicas.

For parameter definition, take a look at CloudSQLDeleteInstanceOperator.

Using the operator

You can create the operator with or without project id. If project id is missing it will be retrieved from the Google Cloud connection used. Both variants are shown:

tests/system/providers/google/cloud/cloud_sql/example_cloud_sql.py[source]

sql_instance_delete_task = CloudSQLDeleteInstanceOperator(
    instance=INSTANCE_NAME, task_id='sql_instance_delete_task'
)

Note: If the instance has read or failover replicas you need to delete them before you delete the primary instance. Replicas are deleted the same way as primary instances:

tests/system/providers/google/cloud/cloud_sql/example_cloud_sql.py[source]

sql_instance_failover_replica_delete_task = CloudSQLDeleteInstanceOperator(
    instance=FAILOVER_REPLICA_NAME,
    task_id='sql_instance_failover_replica_delete_task',
)

sql_instance_read_replica_delete_task = CloudSQLDeleteInstanceOperator(
    instance=READ_REPLICA_NAME, task_id='sql_instance_read_replica_delete_task'
)

Templating

template_fields: Sequence[str] = (
    'project_id',
    'instance',
    'gcp_conn_id',
    'api_version',
    'impersonation_chain',
)

More information

See Google Cloud SQL API documentation to delete a SQL instance.

CloudSQLExportInstanceOperator

Exports data from a Cloud SQL instance to a Cloud Storage bucket as a SQL dump or CSV file.

Note

This operator is idempotent. If executed multiple times with the same export file URI, the export file in GCS will simply be overridden.

For parameter definition take a look at CloudSQLExportInstanceOperator.

Arguments

Example body defining the export operation:

tests/system/providers/google/cloud/cloud_sql/example_cloud_sql.py[source]

export_body = {
    "exportContext": {
        "fileType": "sql",
        "uri": FILE_URI,
        "sqlExportOptions": {"schemaOnly": False},
        "offload": True,
    }
}

Using the operator

You can create the operator with or without project id. If project id is missing it will be retrieved from the Google Cloud connection used. Both variants are shown:

tests/system/providers/google/cloud/cloud_sql/example_cloud_sql.py[source]

sql_export_task = CloudSQLExportInstanceOperator(
    body=export_body, instance=INSTANCE_NAME, task_id='sql_export_task'
)

Templating

template_fields: Sequence[str] = (
    'project_id',
    'instance',
    'body',
    'gcp_conn_id',
    'api_version',
    'impersonation_chain',
)

More information

See Google Cloud SQL API documentation to export data.

Troubleshooting

If you receive an “Unauthorized” error in Google Cloud, make sure that the service account of the Cloud SQL instance is authorized to write to the selected GCS bucket.

It is not the service account configured in Airflow that communicates with GCS, but rather the service account of the particular Cloud SQL instance.

To grant the service account with the appropriate WRITE permissions for the GCS bucket you can use the GCSBucketCreateAclEntryOperator, as shown in the example:

tests/system/providers/google/cloud/cloud_sql/example_cloud_sql.py[source]

sql_gcp_add_bucket_permission_task = GCSBucketCreateAclEntryOperator(
    entity=f"user-{sql_instance_create_task.output['service_account_email']}",
    role="WRITER",
    bucket=file_url_split[1],  # netloc (bucket)
    task_id='sql_gcp_add_bucket_permission_task',
)

CloudSQLImportInstanceOperator

Imports data into a Cloud SQL instance from a SQL dump or CSV file in Cloud Storage.

CSV import:

This operator is NOT idempotent for a CSV import. If the same file is imported multiple times, the imported data will be duplicated in the database. Moreover, if there are any unique constraints the duplicate import may result in an error.

SQL import:

This operator is idempotent for a SQL import if it was also exported by Cloud SQL. The exported SQL contains ‘DROP TABLE IF EXISTS’ statements for all tables to be imported.

If the import file was generated in a different way, idempotence is not guaranteed. It has to be ensured on the SQL file level.

For parameter definition take a look at CloudSQLImportInstanceOperator.

Arguments

Example body defining the import operation:

tests/system/providers/google/cloud/cloud_sql/example_cloud_sql.py[source]

import_body = {"importContext": {"fileType": "sql", "uri": FILE_URI}}

Using the operator

You can create the operator with or without project id. If project id is missing it will be retrieved from the Google Cloud connection used. Both variants are shown:

tests/system/providers/google/cloud/cloud_sql/example_cloud_sql.py[source]

sql_import_task = CloudSQLImportInstanceOperator(
    body=import_body, instance=INSTANCE_NAME, task_id='sql_import_task'
)

Templating

template_fields: Sequence[str] = (
    'project_id',
    'instance',
    'body',
    'gcp_conn_id',
    'api_version',
    'impersonation_chain',
)

More information

See Google Cloud SQL API documentation to import data.

Troubleshooting

If you receive an “Unauthorized” error in Google Cloud, make sure that the service account of the Cloud SQL instance is authorized to read from the selected GCS object.

It is not the service account configured in Airflow that communicates with GCS, but rather the service account of the particular Cloud SQL instance.

To grant the service account with the appropriate READ permissions for the GCS object you can use the GCSBucketCreateAclEntryOperator, as shown in the example:

tests/system/providers/google/cloud/cloud_sql/example_cloud_sql.py[source]

sql_gcp_add_object_permission_task = GCSObjectCreateAclEntryOperator(
    entity=f"user-{sql_instance_create_task.output['service_account_email']}",
    role="READER",
    bucket=file_url_split[1],  # netloc (bucket)
    object_name=file_url_split[2][1:],  # path (strip first '/')
    task_id='sql_gcp_add_object_permission_task',
)

CloudSQLCreateInstanceOperator

Creates a new Cloud SQL instance in Google Cloud.

It is also used for creating read replicas.

For parameter definition, take a look at CloudSQLCreateInstanceOperator.

If an instance with the same name exists, no action will be taken and the operator will succeed.

Arguments

Example body defining the instance with failover replica:

tests/system/providers/google/cloud/cloud_sql/example_cloud_sql.py[source]

body = {
    "name": INSTANCE_NAME,
    "settings": {
        "tier": "db-n1-standard-1",
        "backupConfiguration": {"binaryLogEnabled": True, "enabled": True, "startTime": "05:00"},
        "activationPolicy": "ALWAYS",
        "dataDiskSizeGb": 30,
        "dataDiskType": "PD_SSD",
        "databaseFlags": [],
        "ipConfiguration": {
            "ipv4Enabled": True,
            "requireSsl": True,
        },
        "locationPreference": {"zone": "europe-west4-a"},
        "maintenanceWindow": {"hour": 5, "day": 7, "updateTrack": "canary"},
        "pricingPlan": "PER_USE",
        "replicationType": "ASYNCHRONOUS",
        "storageAutoResize": True,
        "storageAutoResizeLimit": 0,
        "userLabels": {"my-key": "my-value"},
    },
    "failoverReplica": {"name": FAILOVER_REPLICA_NAME},
    "databaseVersion": "MYSQL_5_7",
    "region": "europe-west4",
}

Example body defining read replica for the instance above:

tests/system/providers/google/cloud/cloud_sql/example_cloud_sql.py[source]

read_replica_body = {
    "name": READ_REPLICA_NAME,
    "settings": {
        "tier": "db-n1-standard-1",
    },
    "databaseVersion": "MYSQL_5_7",
    "region": "europe-west4",
    "masterInstanceName": INSTANCE_NAME,
}

Note: Failover replicas are created together with the instance in a single task. Read replicas need to be created in separate tasks.

Using the operator

You can create the operator with or without project id. If project id is missing it will be retrieved from the Google Cloud connection used. Both variants are shown:

tests/system/providers/google/cloud/cloud_sql/example_cloud_sql.py[source]

sql_instance_create_task = CloudSQLCreateInstanceOperator(
    body=body, instance=INSTANCE_NAME, task_id='sql_instance_create_task'
)

Templating

template_fields: Sequence[str] = (
    'project_id',
    'instance',
    'body',
    'gcp_conn_id',
    'api_version',
    'impersonation_chain',
)

More information

See Google Cloud SQL API documentation to create an instance.

CloudSQLInstancePatchOperator

Updates settings of a Cloud SQL instance in Google Cloud (partial update).

For parameter definition, take a look at CloudSQLInstancePatchOperator.

This is a partial update, so only values for the settings specified in the body will be set / updated. The rest of the existing instance’s configuration will remain unchanged.

Arguments

Example body defining the instance:

tests/system/providers/google/cloud/cloud_sql/example_cloud_sql.py[source]

patch_body = {
    "name": INSTANCE_NAME,
    "settings": {
        "dataDiskSizeGb": 35,
        "maintenanceWindow": {"hour": 3, "day": 6, "updateTrack": "canary"},
        "userLabels": {"my-key-patch": "my-value-patch"},
    },
}

Using the operator

You can create the operator with or without project id. If project id is missing it will be retrieved from the Google Cloud connection used. Both variants are shown:

tests/system/providers/google/cloud/cloud_sql/example_cloud_sql.py[source]

sql_instance_patch_task = CloudSQLInstancePatchOperator(
    body=patch_body, instance=INSTANCE_NAME, task_id='sql_instance_patch_task'
)

Templating

template_fields: Sequence[str] = (
    'project_id',
    'instance',
    'body',
    'gcp_conn_id',
    'api_version',
    'impersonation_chain',
)

More information

See Google Cloud SQL API documentation to patch an instance.

CloudSQLExecuteQueryOperator

Performs DDL or DML SQL queries in Google Cloud SQL instance. The DQL (retrieving data from Google Cloud SQL) is not supported. You might run the SELECT queries, but the results of those queries are discarded.

You can specify various connectivity methods to connect to running instance, starting from public IP plain connection through public IP with SSL or both TCP and socket connection via Cloud SQL Proxy. The proxy is downloaded and started/stopped dynamically as needed by the operator.

There is a gcpcloudsql://* connection type that you should use to define what kind of connectivity you want the operator to use. The connection is a “meta” type of connection. It is not used to make an actual connectivity on its own, but it determines whether Cloud SQL Proxy should be started by CloudSQLDatabaseHook and what kind of database connection (Postgres or MySQL) should be created dynamically to connect to Cloud SQL via public IP address or via the proxy. The CloudSqlDatabaseHook uses CloudSqlProxyRunner to manage Cloud SQL Proxy lifecycle (each task has its own Cloud SQL Proxy)

When you build connection, you should use connection parameters as described in CloudSQLDatabaseHook. You can see examples of connections below for all the possible types of connectivity. Such connection can be reused between different tasks (instances of CloudSqlQueryOperator). Each task will get their own proxy started if needed with their own TCP or UNIX socket.

For parameter definition, take a look at CloudSQLExecuteQueryOperator.

Since query operator can run arbitrary query, it cannot be guaranteed to be idempotent. SQL query designer should design the queries to be idempotent. For example, both Postgres and MySQL support CREATE TABLE IF NOT EXISTS statements that can be used to create tables in an idempotent way.

Arguments

If you define connection via AIRFLOW_CONN_{CONN_ID} URL defined in an environment variable, make sure the URL components in the URL are URL-encoded. See examples below for details.

Note that in case of SSL connections you need to have a mechanism to make the certificate/key files available in predefined locations for all the workers on which the operator can run. This can be provided for example by mounting NFS-like volumes in the same path for all the workers.

Example connection definitions for all connectivity cases. Note that all the components of the connection URI should be URL-encoded:

airflow/providers/google/cloud/example_dags/example_cloud_sql_query.py[source]


HOME_DIR = expanduser("~")


def get_absolute_path(path):
    """
    Returns absolute path.
    """
    if path.startswith("/"):
        return path
    else:
        return os.path.join(HOME_DIR, path)


postgres_kwargs = dict(
    user=quote_plus(GCSQL_POSTGRES_USER),
    password=quote_plus(GCSQL_POSTGRES_PASSWORD),
    public_port=GCSQL_POSTGRES_PUBLIC_PORT,
    public_ip=quote_plus(GCSQL_POSTGRES_PUBLIC_IP),
    project_id=quote_plus(GCP_PROJECT_ID),
    location=quote_plus(GCP_REGION),
    instance=quote_plus(GCSQL_POSTGRES_INSTANCE_NAME_QUERY),
    database=quote_plus(GCSQL_POSTGRES_DATABASE_NAME),
    client_cert_file=quote_plus(get_absolute_path(GCSQL_POSTGRES_CLIENT_CERT_FILE)),
    client_key_file=quote_plus(get_absolute_path(GCSQL_POSTGRES_CLIENT_KEY_FILE)),
    server_ca_file=quote_plus(get_absolute_path(GCSQL_POSTGRES_SERVER_CA_FILE)),
)

# The connections below are created using one of the standard approaches - via environment
# variables named AIRFLOW_CONN_* . The connections can also be created in the database
# of AIRFLOW (using command line or UI).

# Postgres: connect via proxy over TCP
os.environ['AIRFLOW_CONN_PROXY_POSTGRES_TCP'] = (
    "gcpcloudsql://{user}:{password}@{public_ip}:{public_port}/{database}?"
    "database_type=postgres&"
    "project_id={project_id}&"
    "location={location}&"
    "instance={instance}&"
    "use_proxy=True&"
    "sql_proxy_use_tcp=True".format(**postgres_kwargs)
)

# Postgres: connect via proxy over UNIX socket (specific proxy version)
os.environ['AIRFLOW_CONN_PROXY_POSTGRES_SOCKET'] = (
    "gcpcloudsql://{user}:{password}@{public_ip}:{public_port}/{database}?"
    "database_type=postgres&"
    "project_id={project_id}&"
    "location={location}&"
    "instance={instance}&"
    "use_proxy=True&"
    "sql_proxy_version=v1.13&"
    "sql_proxy_use_tcp=False".format(**postgres_kwargs)
)

# Postgres: connect directly via TCP (non-SSL)
os.environ['AIRFLOW_CONN_PUBLIC_POSTGRES_TCP'] = (
    "gcpcloudsql://{user}:{password}@{public_ip}:{public_port}/{database}?"
    "database_type=postgres&"
    "project_id={project_id}&"
    "location={location}&"
    "instance={instance}&"
    "use_proxy=False&"
    "use_ssl=False".format(**postgres_kwargs)
)

# Postgres: connect directly via TCP (SSL)
os.environ['AIRFLOW_CONN_PUBLIC_POSTGRES_TCP_SSL'] = (
    "gcpcloudsql://{user}:{password}@{public_ip}:{public_port}/{database}?"
    "database_type=postgres&"
    "project_id={project_id}&"
    "location={location}&"
    "instance={instance}&"
    "use_proxy=False&"
    "use_ssl=True&"
    "sslcert={client_cert_file}&"
    "sslkey={client_key_file}&"
    "sslrootcert={server_ca_file}".format(**postgres_kwargs)
)

mysql_kwargs = dict(
    user=quote_plus(GCSQL_MYSQL_USER),
    password=quote_plus(GCSQL_MYSQL_PASSWORD),
    public_port=GCSQL_MYSQL_PUBLIC_PORT,
    public_ip=quote_plus(GCSQL_MYSQL_PUBLIC_IP),
    project_id=quote_plus(GCP_PROJECT_ID),
    location=quote_plus(GCP_REGION),
    instance=quote_plus(GCSQL_MYSQL_INSTANCE_NAME_QUERY),
    database=quote_plus(GCSQL_MYSQL_DATABASE_NAME),
    client_cert_file=quote_plus(get_absolute_path(GCSQL_MYSQL_CLIENT_CERT_FILE)),
    client_key_file=quote_plus(get_absolute_path(GCSQL_MYSQL_CLIENT_KEY_FILE)),
    server_ca_file=quote_plus(get_absolute_path(GCSQL_MYSQL_SERVER_CA_FILE)),
)

# MySQL: connect via proxy over TCP (specific proxy version)
os.environ['AIRFLOW_CONN_PROXY_MYSQL_TCP'] = (
    "gcpcloudsql://{user}:{password}@{public_ip}:{public_port}/{database}?"
    "database_type=mysql&"
    "project_id={project_id}&"
    "location={location}&"
    "instance={instance}&"
    "use_proxy=True&"
    "sql_proxy_version=v1.13&"
    "sql_proxy_use_tcp=True".format(**mysql_kwargs)
)

# MySQL: connect via proxy over UNIX socket using pre-downloaded Cloud Sql Proxy binary
try:
    sql_proxy_binary_path = subprocess.check_output(['which', 'cloud_sql_proxy']).decode('utf-8').rstrip()
except subprocess.CalledProcessError:
    sql_proxy_binary_path = "/tmp/anyhow_download_cloud_sql_proxy"

os.environ['AIRFLOW_CONN_PROXY_MYSQL_SOCKET'] = (
    "gcpcloudsql://{user}:{password}@{public_ip}:{public_port}/{database}?"
    "database_type=mysql&"
    "project_id={project_id}&"
    "location={location}&"
    "instance={instance}&"
    "use_proxy=True&"
    "sql_proxy_binary_path={sql_proxy_binary_path}&"
    "sql_proxy_use_tcp=False".format(sql_proxy_binary_path=quote_plus(sql_proxy_binary_path), **mysql_kwargs)
)

# MySQL: connect directly via TCP (non-SSL)
os.environ['AIRFLOW_CONN_PUBLIC_MYSQL_TCP'] = (
    "gcpcloudsql://{user}:{password}@{public_ip}:{public_port}/{database}?"
    "database_type=mysql&"
    "project_id={project_id}&"
    "location={location}&"
    "instance={instance}&"
    "use_proxy=False&"
    "use_ssl=False".format(**mysql_kwargs)
)

# MySQL: connect directly via TCP (SSL) and with fixed Cloud Sql Proxy binary path
os.environ['AIRFLOW_CONN_PUBLIC_MYSQL_TCP_SSL'] = (
    "gcpcloudsql://{user}:{password}@{public_ip}:{public_port}/{database}?"
    "database_type=mysql&"
    "project_id={project_id}&"
    "location={location}&"
    "instance={instance}&"
    "use_proxy=False&"
    "use_ssl=True&"
    "sslcert={client_cert_file}&"
    "sslkey={client_key_file}&"
    "sslrootcert={server_ca_file}".format(**mysql_kwargs)
)

# Special case: MySQL: connect directly via TCP (SSL) and with fixed Cloud Sql
# Proxy binary path AND with missing project_id

os.environ['AIRFLOW_CONN_PUBLIC_MYSQL_TCP_SSL_NO_PROJECT_ID'] = (
    "gcpcloudsql://{user}:{password}@{public_ip}:{public_port}/{database}?"
    "database_type=mysql&"
    "location={location}&"
    "instance={instance}&"
    "use_proxy=False&"
    "use_ssl=True&"
    "sslcert={client_cert_file}&"
    "sslkey={client_key_file}&"
    "sslrootcert={server_ca_file}".format(**mysql_kwargs)
)


Using the operator

Example operators below are using all connectivity options. Note connection id from the operator matches the AIRFLOW_CONN_{CONN_ID} postfix uppercase. This is standard AIRFLOW notation for defining connection via environment variables):

airflow/providers/google/cloud/example_dags/example_cloud_sql_query.py[source]


connection_names = [
    "proxy_postgres_tcp",
    "proxy_postgres_socket",
    "public_postgres_tcp",
    "public_postgres_tcp_ssl",
    "proxy_mysql_tcp",
    "proxy_mysql_socket",
    "public_mysql_tcp",
    "public_mysql_tcp_ssl",
    "public_mysql_tcp_ssl_no_project_id",
]

tasks = []


with models.DAG(
    dag_id='example_gcp_sql_query',
    schedule_interval='@once',
    start_date=datetime(2021, 1, 1),
    catchup=False,
    tags=['example'],
) as dag:
    prev_task = None

    for connection_name in connection_names:
        task = CloudSQLExecuteQueryOperator(
            gcp_cloudsql_conn_id=connection_name, task_id="example_gcp_sql_task_" + connection_name, sql=SQL
        )
        tasks.append(task)
        if prev_task:
            prev_task >> task
        prev_task = task

Templating

template_fields: Sequence[str] = ('sql', 'gcp_cloudsql_conn_id', 'gcp_conn_id')
template_ext: Sequence[str] = ('.sql',)
template_fields_renderers = {'sql': 'sql'}

More information

See Google Cloud SQL documentation for MySQL and PostgreSQL related proxies.

Was this entry helpful?