|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 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 __future__ import annotations |
| 16 | + |
| 17 | +from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union |
| 18 | + |
| 19 | +if TYPE_CHECKING: |
| 20 | + from aws_advanced_python_wrapper.pep249 import Connection |
| 21 | + |
| 22 | +import psycopg # type: ignore |
| 23 | + |
| 24 | +from aws_advanced_python_wrapper import AwsWrapperConnection |
| 25 | +from aws_advanced_python_wrapper.errors import ( |
| 26 | + FailoverFailedError, FailoverSuccessError, |
| 27 | + TransactionResolutionUnknownError) |
| 28 | +from aws_advanced_python_wrapper.host_monitoring_plugin import MonitoringThreadContainer |
| 29 | + |
| 30 | +def configure_initial_session_states(conn: Connection): |
| 31 | + awscursor = conn.cursor() |
| 32 | + awscursor.execute("SET TIME ZONE 'UTC'") |
| 33 | + |
| 34 | + |
| 35 | +def execute_queries_with_failover_handling(conn: Connection, sql: str, params: Optional[Union[Dict, Tuple]] = None): |
| 36 | + try: |
| 37 | + cursor = conn.cursor() |
| 38 | + cursor.execute(sql, params) |
| 39 | + return cursor |
| 40 | + |
| 41 | + except FailoverSuccessError: |
| 42 | + # Query execution failed and AWS Advanced Python Driver successfully failed over to an available instance. |
| 43 | + # https://github.com/awslabs/aws-advanced-python-wrapper/blob/main/docs/using-the-python-driver/using-plugins/UsingTheFailoverPlugin.md#FailoverFailedError---successful-failover |
| 44 | + |
| 45 | + # The old cursor is no longer reusable and the application needs to reconfigure sessions states. |
| 46 | + configure_initial_session_states(conn) |
| 47 | + # Retry query |
| 48 | + cursor = conn.cursor() |
| 49 | + cursor.execute(sql) |
| 50 | + return cursor |
| 51 | + |
| 52 | + except FailoverFailedError as e: |
| 53 | + # User application should open a new connection, check the results of the failed transaction and re-run it if needed. See: |
| 54 | + # https://github.com/awslabs/aws-advanced-python-wrapper/blob/main/docs/using-the-python-driver/using-plugins/UsingTheFailoverPlugin.md#FailoverFailedError---unable-to-establish-sql-connection |
| 55 | + raise e |
| 56 | + |
| 57 | + except TransactionResolutionUnknownError as e: |
| 58 | + # User application should check the status of the failed transaction and restart it if needed. See: |
| 59 | + # https://github.com/awslabs/aws-advanced-python-wrapper/blob/main/docs/using-the-python-driver/using-plugins/UsingTheFailoverPlugin.md#TransactionResolutionUnknownError---transaction-resolution-unknown |
| 60 | + raise e |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + params = { |
| 65 | + "host": "database.cluster-xyz.us-east-1.rds.amazonaws.com", |
| 66 | + "dbname": "postgres", |
| 67 | + "user": "john", |
| 68 | + "password": "pwd", |
| 69 | + "plugins": "srw,failover", |
| 70 | + "srw_write_endpoint": "database.cluster-xyz.us-east-1.rds.amazonaws.com", # Replace with write endpoint |
| 71 | + "srw_read_endpoint": "database.cluster-ro-xyz.us-east-1.rds.amazonaws.com", # Replace with read endpoint |
| 72 | + "srw_verify_new_connections": "True", # Enables role-verification for new endpoints |
| 73 | + "wrapper_dialect": "aurora-pg", |
| 74 | + "autocommit": True |
| 75 | + } |
| 76 | + |
| 77 | + """ Setup step: open connection and create tables """ |
| 78 | + with AwsWrapperConnection.connect(psycopg.Connection.connect, **params) as conn: |
| 79 | + configure_initial_session_states(conn) |
| 80 | + execute_queries_with_failover_handling( |
| 81 | + conn, "CREATE TABLE IF NOT EXISTS bank_test (id int primary key, name varchar(40), account_balance int)") |
| 82 | + execute_queries_with_failover_handling( |
| 83 | + conn, "INSERT INTO bank_test VALUES (%s, %s, %s)", (0, "Jane Doe", 200)) |
| 84 | + execute_queries_with_failover_handling( |
| 85 | + conn, "INSERT INTO bank_test VALUES (%s, %s, %s)", (1, "John Smith", 200)) |
| 86 | + |
| 87 | + """ Example step: open connection and perform transaction """ |
| 88 | + try: |
| 89 | + with AwsWrapperConnection.connect(psycopg.Connection.connect, **params) as conn, conn.cursor() as cursor: |
| 90 | + configure_initial_session_states(conn) |
| 91 | + |
| 92 | + execute_queries_with_failover_handling( |
| 93 | + conn, "UPDATE bank_test SET account_balance=account_balance - 100 WHERE name=%s", ("Jane Doe",)) |
| 94 | + execute_queries_with_failover_handling( |
| 95 | + conn, "UPDATE bank_test SET account_balance=account_balance + 100 WHERE name=%s", ("John Smith",)) |
| 96 | + |
| 97 | + # Internally switch to a reader connection |
| 98 | + conn.read_only = True |
| 99 | + for i in range(2): |
| 100 | + cursor = execute_queries_with_failover_handling(conn, "SELECT * FROM bank_test WHERE id = %s", (i,)) |
| 101 | + results = cursor.fetchall() |
| 102 | + for record in results: |
| 103 | + print(record) |
| 104 | + |
| 105 | + finally: |
| 106 | + with AwsWrapperConnection.connect(psycopg.Connection.connect, **params) as conn: |
| 107 | + execute_queries_with_failover_handling(conn, "DROP TABLE bank_test") |
0 commit comments