Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions google/cloud/sql/connector/connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,10 @@

import google.cloud.sql.connector.asyncpg as asyncpg
from google.cloud.sql.connector.client import CloudSQLClient
from google.cloud.sql.connector.enums import DriverMapping
from google.cloud.sql.connector.exceptions import ConnectorLoopError
from google.cloud.sql.connector.exceptions import DnsNameResolutionError
from google.cloud.sql.connector.exceptions import IncompatibleDriverError
from google.cloud.sql.connector.instance import IPTypes
from google.cloud.sql.connector.instance import RefreshAheadCache
from google.cloud.sql.connector.instance import RefreshStrategy
Expand Down Expand Up @@ -321,6 +323,14 @@ async def connect_async(
# attempt to make connection to Cloud SQL instance
try:
conn_info = await cache.connect_info()
# validate driver matches intended database engine
mapping = DriverMapping[driver.upper()]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if we encapsulated more details and did something like this?

conn_info = await cache.connect_info()
if not DriverMapping.matching_engine(driver, conn_info.database_version):
    raise IncompatibleDriverError

where the DriverMapping method looks like:

class DriverMapping(Enum):
    def matching_engine(driver: str, engine: str) -> bool:
        return engine.startswith(DriverMapping[driver.upper()])

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this would mean i no longer have access to the proper compatible database engine mapping.value in the error message without doing a separate call to DriverMapping[driver.upper()].value which is more work...

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just an idea -- feel free to handle it however you like. A good error message is most important.

if not conn_info.database_version.startswith(mapping.value):
raise IncompatibleDriverError(
f"Database driver '{driver}' is incompatible with database "
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a fatal configuration error. I think the message could be more clear. Something like:

"Fatal Error: the Cloud SQL Connector is configured with an incompatible database driver. Configured driver '{driver}' cannot connect to database instance '{instance_connection_string}' running version {conn_info.database_version}."

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hessjcg I don't normally see Python errors get prefixed with "Fatal Error:", its more the assumption that if an error is raised from the application it must be fatal.

I like the error message as is personally, concise and actionable. I don't have access to instance_connection_string from where the error is raised after the encapsulation refactor...

f"version '{conn_info.database_version}'. Given driver can "
f"only be used with Cloud SQL {mapping.value} databases."
)
ip_address = conn_info.get_preferred_ip(ip_type)
# resolve DNS name into IP address for PSC
if ip_type.value == "PSC":
Expand Down
24 changes: 24 additions & 0 deletions google/cloud/sql/connector/enums.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from enum import Enum


class DriverMapping(Enum):
"""Maps a given database driver to it's corresponding database engine."""

ASYNCPG = "POSTGRES"
PG8000 = "POSTGRES"
PYMYSQL = "MYSQL"
PYTDS = "SQLSERVER"
Comment on lines +20 to +26
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am going to have a follow-up refactor PR that moves the other shared enum types (IPTypes, RefreshStrategy) out of instance.py and into this file.

7 changes: 7 additions & 0 deletions google/cloud/sql/connector/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,10 @@ class RefreshNotValidError(Exception):
"""

pass


class IncompatibleDriverError(Exception):
"""
Exception to be raised when the database driver given is for the wrong
database engine. (i.e. asyncpg for a MySQL database)
"""
26 changes: 25 additions & 1 deletion tests/unit/test_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
See the License for the specific language governing permissions and
limitations under the License.
"""

import asyncio
from typing import Union

Expand All @@ -25,6 +26,7 @@
from google.cloud.sql.connector import IPTypes
from google.cloud.sql.connector.client import CloudSQLClient
from google.cloud.sql.connector.exceptions import ConnectorLoopError
from google.cloud.sql.connector.exceptions import IncompatibleDriverError
from google.cloud.sql.connector.instance import RefreshAheadCache


Expand All @@ -46,10 +48,32 @@ def test_connect_enable_iam_auth_error(
"If you require both for your use case, please use a new "
"connector.Connector object."
)
# remove cache entrry to avoid destructor warnings
# remove cache entry to avoid destructor warnings
connector._cache = {}


async def test_connect_incompatible_driver_error(
fake_credentials: Credentials,
fake_client: CloudSQLClient,
) -> None:
"""Test that calling connect() with driver that is incompatible with
database version throws error."""
connect_string = "test-project:test-region:test-instance"
async with Connector(
credentials=fake_credentials, loop=asyncio.get_running_loop()
) as connector:
connector._client = fake_client
# try to connect using pymysql driver to a Postgres database
with pytest.raises(IncompatibleDriverError) as exc_info:
await connector.connect_async(connect_string, "pymysql")
assert (
exc_info.value.args[0]
== "Database driver 'pymysql' is incompatible with database version"
" 'POSTGRES_15'. Given driver can only be used with Cloud SQL MYSQL"
" databases."
)


def test_connect_with_unsupported_driver(fake_credentials: Credentials) -> None:
with Connector(credentials=fake_credentials) as connector:
# try to connect using unsupported driver, should raise KeyError
Expand Down