Superdooperhero
Superdooperhero

Reputation: 8106

Execute text in Postgresql database as Python code

If I have text that is saved in a Postgresql database is there any way to execute that text as Python code and potentially have it update the same database?

Upvotes: 0

Views: 246

Answers (2)

Chris Farmiloe
Chris Farmiloe

Reputation: 14185

  1. That sounds terrifying.
  2. Yes, plpy

PL/Python is a extension for postgres that lets you write functions in python. You may have to install the extension from your package manager or it may have been bundled in already when you installed postgres (this depends on how you installed postgres apt-get install postgresql-plpython-9.1 in debian).

To enable the extension in your database first use psql to run:

CREATE EXTENSION plpythonu

Now you can specify functions with python so you could write a function to execute that code like:

CREATE FUNCTION eval_python(code text) RETURNS integer AS $$
    eval(code)
    return 1
$$ LANGUAGE plpythonu;

And execute it for every code field in my_table like:

SELECT eval_python(code) FROM my_table;

Read the docs on PL/python for more details on how to interact with the db from python.

Upvotes: 1

Brad
Brad

Reputation: 1377

let me see if I understand what you are trying to accomplish:

  1. store ad-hoc user code in a varchar field on a database
  2. read and execute said code
  3. allow said code to affect the database in question, say drop table ...

Assuming that I've got it, you could write something that

  1. reads the table holding the code (use pyodbc or something)
  2. runs an eval on what was pulled from the db - this will let you execute ANY code, including self updating code

are you sure this is what you want to do?

Upvotes: 0

Related Questions