2

I have a sql where that I have formatted with new lines and multiple tabs and spaces. I have this for example, but indented multiple times:

q = f'''
    UPDATE
        `table`
    SET
        `col1` = 1
    WHERE
        `another col` = 2
    AND 
        `final col` = 3
    '''

How can I convert the query into a single line?

4 Answers 4

1

You can use

width = 100
textwrap.shorten(q, width)

giving

'UPDATE `table` SET `col1` = 1 WHERE `another col` = 2 AND `final col` = 3'

but you need to be careful if the SQL values contain multiple spaces, for example

SET `col1` = "a  b  c"

as they will be collapsed too.

Sign up to request clarification or add additional context in comments.

Comments

0

For IDLE editor, use Alt+Q to bring selected code in one single line.

Comments

0

SQL databases are not too fussy about SQL formatting. They will take multi-line or single line queries just fine. For readability (for humans), a multi-line string is often preferred.

Here's your one liner:

q = "UPDATE `table` SET `col1` = 1 WHERE `another col` = 2 AND `final col` = 3"

I kept your backticks ``, but I don't really know what they're for. Maybe some DBs use backtick for tables or columns that have spaces in their names?

Comments

0

This solution uses the shlex.shlex class to

  1. Preserve quote (the back tick) `
  2. Preserve number of spaces inside the the quotes
import shlex

q = f'''
    UPDATE
        `table`
    SET
        `col1` = 1
    WHERE
        `another col` = 2
    AND 
        `final col` = 3
'''

tokens = shlex.shlex(q)
tokens.quotes += "`"  # The back tick is consider a quote char
new_q = " ".join(tokens)
print(new_q)

Output:

UPDATE `table` SET `col1` = 1 WHERE `another col` = 2 AND `final col` = 3

Notes

  • The shlex.shlex class can split a text into tokens, which are separated by one or more spaces
  • I also tell shlex to consider the back tick as a quote char, which preserves the spaces within
  • Using this class is much better than using str.split because it understands quotes, whereas str.split does not.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.