Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format long SQL queries according to PEP8

According to PEP 8 (Maximum Line Length), a line should never be longer than 79 characters.

When I try to split up queries, however, I run into issues like continuation characters, and invalid tokens, etc.

For example, what would be the best way to format this query, according to PEP8?

cursor.execute("SELECT pivot_id FROM aud_qty WHERE hshake1 is NULL AND ((strftime('%s', DATETIME('now')) - strftime('%s', sent_to_pivot)) / (60)) > 30;")
like image 680
flybonzai Avatar asked Sep 23 '15 23:09

flybonzai


2 Answers

What about

cursor.execute("""SELECT pivot_id
                    FROM aud_qty
                   WHERE hshake1 is NULL
                     AND ((strftime('%s', DATETIME('now')) -
                         strftime('%s', sent_to_pivot)) / (60)) > 30;
               """)

? Using """ or ''' you get the same behaviour as a very long string but you can use newlines just fine. And your database won't mind them either.

like image 61
Johannes Weiss Avatar answered Sep 28 '22 06:09

Johannes Weiss


In this way you have a clearly looking SQL statement that complies with PEP8 guidelines.

cursor.execute("""
    SELECT pivot_id
    FROM aud_qty
    WHERE hshake1 is NULL
        AND ((strftime('%s', DATETIME('now')) -
            strftime('%s', sent_to_pivot)) / (60)) > 30;
""")
like image 23
Arturo Avatar answered Sep 28 '22 04:09

Arturo