0

I have a management command running on an EC2 instance which fails when trying to execute ORM queries like so:

  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 53, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 899, in execute_sql
    raise original_exception
OperationalError: SSL connection has been closed unexpectedly

I can connect to the same database just fine from a django-admin shell_plus on the same instance.

To diagnose this, I'd like to inspect the parameters of the connection request Django is making in each case, to see what's different, but after a bit of poking through the Django source it seemed best to ask how rather than getting lost in the weeds for hours :)

alternate strategies for diagnosing this also welcome!

Personman
  • 2,324
  • 1
  • 16
  • 27
  • One of the answers from [here](https://stackoverflow.com/questions/4375784/log-all-sql-queries) could help and also [this](https://getkt.com/blog/how-to-view-converted-sql-queries-of-django-orm/). You just may want to log into file instead of stdout or whatever. – Charnel Feb 03 '20 at 21:39
  • I don't want to log queries — I want to log the parameters of the _connection request_. No queries can be made, because the connection gets broken. – Personman Feb 03 '20 at 22:11
  • Maybe you then need to specify in the question that you want to log remote requests to DB. – Charnel Feb 03 '20 at 22:26
  • Which database are you using? (e.g. PostgreSQL, MySQL, Oracle, etc.). It might be possible to inspect requests on the database side. – Flux Feb 04 '20 at 03:22

2 Answers2

0

According to the documentation about logging database queries, you should look in your database log files:

This logging does not include framework-level initialization (e.g. SET TIMEZONE) or transaction management queries (e.g. BEGIN, COMMIT, and ROLLBACK). Turn on query logging in your database if you wish to view all database queries.

Flux
  • 9,805
  • 5
  • 46
  • 92
0

I've gotten to the bottom of this: the issue was that this management command was daemonized, DB connections do not survive fork(), and Django is not smart enough to notice, so it tries to use the dead connection and breaks.

The solution is

from django.db import close_old_connections

class Daemon():
    def start()
        self.daemonize()
        close_old_connections()
Personman
  • 2,324
  • 1
  • 16
  • 27