Is there a hook to run an SQL Query at every Postgres session start?

178 views
Skip to first unread message

Bobby Mozumder

unread,
Feb 3, 2016, 12:25:36 PM2/3/16
to Django users
I'm looking to use PREPARE/EXECUTE statements, to eliminate my Query Planning time from every Web request.

This can be done via SQL PREPARE/EXECUTE statements.

But, Postgres only supports PREPARE statements on a connection session-by-session basis.  

To do this with Django, I need to be able to run an SQL Query that runs the PREPARE statement for every connection to the Database. I only need to do this once per DB connection, as I have enabled Persistent connections.  

The code to run, if I put it into the App.view, would be something like this:

class PreparedView(View):
    def prepare_db():
        cursor = connection.cursor()
        cursor.execute(“”"
PREPARE prepared_query (int, text, etc) AS
  SELECT … some query … 
“”"
        return cursor.close()

I’m looking through the Django code to see where I can run some sort of Query.  Maybe I can subclass django.db.backends.postgresql.base.DatabaseWrapper.init_db_connection_state()?

Also, where can I hook that into my app?  If I subclass that, I’m not sure if I can/should put that in the Model, View, or URL of modules of my app, so that it’s called?  Do I create an entirely new version of django.db.backends.postgresql?

Ideally this would work with both the basic built-in development server connecting to a local host Postgres, as well as in a uWSGI environment with possible pgBouncer in the stack somewhere.

Thanks!

-bobby

Simon Charette

unread,
Feb 3, 2016, 12:34:38 PM2/3/16
to Django users
Hi Bobby,

I'm not sure this is what you are looking for but it looks like `connection_created`[1] signal might do.

Cheers,
Simon

[1] https://docs.djangoproject.com/en/1.9/ref/signals/#connection-created

Bobby Mozumder

unread,
Feb 3, 2016, 8:47:07 PM2/3/16
to django...@googlegroups.com
Thanks Simon this works great so far =^)

-bobby

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/06a0a777-9823-4112-9683-131e277d0c2b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages