[파이썬] Psycopg2에서 Event triggers 및 listen/notify

Psycopg2 is a popular Python library for connecting to PostgreSQL databases. It provides a wide range of features that enable developers to interact with PostgreSQL efficiently. In this blog post, we will explore how to use Psycopg2 to work with event triggers and listen/notify functionality in PostgreSQL.

Event triggers in PostgreSQL allow us to execute custom code when specific events occur within the database. This is particularly useful when we want to automate certain actions based on database events, such as data changes or schema modifications. Psycopg2 provides a simple and straightforward way to create and manage event triggers in Python.

To create an event trigger using Psycopg2, we can use the execute() method of the connection object. Here’s an example:

import psycopg2

# Connect to the PostgreSQL database
conn = psycopg2.connect(database="mydatabase", user="myuser", password="mypassword", host="localhost", port="5432")

# Create an event trigger
trigger_sql = """
CREATE EVENT TRIGGER my_trigger
ON ddl_command_end
EXECUTE FUNCTION my_trigger_function();
"""

# Execute the trigger creation statement
conn.cursor().execute(trigger_sql)

# Commit the changes
conn.commit()

# Close the connection
conn.close()

In this example, we first establish a connection to the PostgreSQL database using the connect() method. We then create an event trigger using the SQL statement defined in the trigger_sql variable. The ON ddl_command_end specifies that the trigger should be fired after each DDL command execution. Finally, we execute the trigger creation statement using the execute() method and commit the changes to the database.

Now let’s look at how to utilize the listen/notify functionality in Psycopg2. Listen/notify is a mechanism provided by PostgreSQL to send notifications from the database to the connected clients. This can be useful in scenarios where we need to notify the Python application about specific events occurring in the database.

Here’s an example of how to use listen/notify with Psycopg2:

import psycopg2.extensions

# Connect to the PostgreSQL database
conn = psycopg2.connect(database="mydatabase", user="myuser", password="mypassword", host="localhost", port="5432")

# Enable asynchronous mode
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)

# Create a new cursor
cur = conn.cursor()

# Listen for a specific channel
cur.execute("LISTEN mychannel;")

# Wait for notifications
while True:
    # Receive notifications
    conn.poll()

    # Process received notifications
    while conn.notifies:
        notification = conn.notifies.pop(0)
        print(f"Received notification: {notification.channel}: {notification.payload}")

# Close the connection
conn.close()

In this example, we first establish a connection to the PostgreSQL database. We then set the isolation level to ISOLATION_LEVEL_AUTOCOMMIT to enable asynchronous mode. This allows us to receive notifications without blocking other operations. Next, we create a new cursor and use the execute() method to listen for notifications on a specific channel. Finally, we enter a loop where we continuously call poll() to receive notifications and process them accordingly.

Psycopg2 provides a convenient way to work with event triggers and listen/notify functionality in PostgreSQL. By leveraging these features, you can build powerful and reactive applications that respond to database events in real-time.