|
| 1 | +# Copyright 2024 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from datetime import datetime |
| 16 | +import os |
| 17 | +from typing import Tuple |
| 18 | + |
| 19 | +from gevent import monkey |
| 20 | + |
| 21 | +monkey.patch_all() |
| 22 | + |
| 23 | +import pg8000 |
| 24 | +import sqlalchemy |
| 25 | + |
| 26 | +from google.cloud.sql.connector import Connector |
| 27 | + |
| 28 | + |
| 29 | +def create_sqlalchemy_engine( |
| 30 | + instance_connection_name: str, |
| 31 | + user: str, |
| 32 | + password: str, |
| 33 | + db: str, |
| 34 | + refresh_strategy: str = "background", |
| 35 | +) -> Tuple[sqlalchemy.engine.Engine, Connector]: |
| 36 | + """Creates a connection pool for a Cloud SQL instance and returns the pool |
| 37 | + and the connector. Callers are responsible for closing the pool and the |
| 38 | + connector. |
| 39 | +
|
| 40 | + A sample invocation looks like: |
| 41 | +
|
| 42 | + engine, connector = create_sqlalchemy_engine( |
| 43 | + inst_conn_name, |
| 44 | + user, |
| 45 | + password, |
| 46 | + db, |
| 47 | + ) |
| 48 | + with engine.connect() as conn: |
| 49 | + time = conn.execute(sqlalchemy.text("SELECT NOW()")).fetchone() |
| 50 | + conn.commit() |
| 51 | + curr_time = time[0] |
| 52 | + # do something with query result |
| 53 | + connector.close() |
| 54 | +
|
| 55 | + Args: |
| 56 | + instance_connection_name (str): |
| 57 | + The instance connection name specifies the instance relative to the |
| 58 | + project and region. For example: "my-project:my-region:my-instance" |
| 59 | + user (str): |
| 60 | + The database user name, e.g., postgres |
| 61 | + password (str): |
| 62 | + The database user's password, e.g., secret-password |
| 63 | + db (str): |
| 64 | + The name of the database, e.g., mydb |
| 65 | + refresh_strategy (Optional[str]): |
| 66 | + Refresh strategy for the Cloud SQL Connector. Can be one of "lazy" |
| 67 | + or "background". For serverless environments use "lazy" to avoid |
| 68 | + errors resulting from CPU being throttled. |
| 69 | + """ |
| 70 | + connector = Connector(refresh_strategy=refresh_strategy) |
| 71 | + |
| 72 | + def getconn() -> pg8000.dbapi.Connection: |
| 73 | + conn: pg8000.dbapi.Connection = connector.connect( |
| 74 | + instance_connection_name, |
| 75 | + "pg8000", |
| 76 | + user=user, |
| 77 | + password=password, |
| 78 | + db=db, |
| 79 | + ip_type="public", # can also be "private" or "psc" |
| 80 | + ) |
| 81 | + return conn |
| 82 | + |
| 83 | + # create SQLAlchemy connection pool |
| 84 | + engine = sqlalchemy.create_engine( |
| 85 | + "postgresql+pg8000://", |
| 86 | + creator=getconn, |
| 87 | + ) |
| 88 | + return engine, connector |
| 89 | + |
| 90 | + |
| 91 | +def test_gevent_pg8000_connection() -> None: |
| 92 | + """Basic test to get time from database with gevent.""" |
| 93 | + inst_conn_name = os.environ["POSTGRES_CONNECTION_NAME"] |
| 94 | + user = os.environ["POSTGRES_USER"] |
| 95 | + password = os.environ["POSTGRES_PASS"] |
| 96 | + db = os.environ["POSTGRES_DB"] |
| 97 | + |
| 98 | + engine, connector = create_sqlalchemy_engine(inst_conn_name, user, password, db) |
| 99 | + with engine.connect() as conn: |
| 100 | + time = conn.execute(sqlalchemy.text("SELECT NOW()")).fetchone() |
| 101 | + conn.commit() |
| 102 | + curr_time = time[0] |
| 103 | + assert type(curr_time) is datetime |
| 104 | + connector.close() |
0 commit comments