To begin, make sure you have Psycopg2
installed. If you don’t have it already, you can install it using pip
:
pip install psycopg2
Once you have Psycopg2
installed, let’s create a simple server-side function that retrieves data from a PostgreSQL database using PL/Python. Here’s an example:
CREATE OR REPLACE FUNCTION get_user_details(user_id INTEGER)
RETURNS JSONB
LANGUAGE plpython3u
AS $$
import psycopg2
def get_user_details(user_id):
conn = psycopg2.connect(
host="your_host",
port=5432,
database="your_database",
user="your_user",
password="your_password"
)
cursor = conn.cursor()
cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")
user_data = cursor.fetchone()
cursor.close()
conn.close()
# Convert the user data to a dictionary and return as JSON
return {"id": user_data[0], "name": user_data[1], "email": user_data[2]}
return get_user_details(user_id)
$$;
In the above example, we define a server-side function get_user_details
, which takes a user_id
as input and returns the user details as JSON. Inside the function, we establish a connection to the PostgreSQL database using psycopg2.connect
. We then execute a SQL query to fetch the user data and convert it into JSON format before returning it.
To use the get_user_details
function, you can simply call it in a SQL query like this:
SELECT get_user_details(1);
This will return the user details of the user with id
equal to 1.
Server-side programming with PL/Python
and Psycopg2
provides a flexible and powerful way to work with PostgreSQL databases. You can leverage the full power of Python and Psycopg2
to perform complex data processing, calculations, and more directly within the database engine.
That’s it for this blog post! We explored the usage of Psycopg2
for server-side programming with PL/Python
in PostgreSQL. Hope you found it helpful and stay tuned for more informative blog posts.