简体   繁体   中英

Paste a formatted and higlighted multiline text (SQL) into string literal in PyCharm

Is there a way in PyCharm to paste multiline text (SQL) into string literal? Eg:

SELECT column1
     , column2
FROM table1
WHERE column3 IN
(
    SELECT TOP(1) column4
    FROM table2
    INNER JOIN table3
    ON table2.column1 = table3.column1
)

Into:

sql = (
    "SELECT column1"
    "     , column2"
    "FROM table1"
    "..."
)

And ideally tell PyCharm it is text in SQL language to highlight syntax?

Is there a way in PyCharm to paste multiline text (SQL) into string literal?

Yes. First you'll have to "Create a live template" and since you want to paste the right function to use would be clipboard() . You can do this by going to File > Settings > Editor > Live Templates as shown in the screenshot.

在此处输入图像描述

And ideally tell PyCharm it is text in SQL language to highlight syntax?

Yes. You can do this by using "language injection" in the code segment. If you have it preconfiguered like shown in the following screenshot PyCharm should autodetect SQL and apply the syntax highlight. It can be set at File > Settings > Editor > Intention .

在此处输入图像描述

If you don't have the intention set to autodetect you can also do it manually by right-clicking and choosing "Show Context Actions" or pressing the light-bulb in the code (this is made easier by putting the SQL code inside a string).

在此处输入图像描述

After choosing the SQL dialect you prefer, you can also fine-tune syntax highlight and syntax checks of the injected language.

Functionalities IDE path to dialogue
Syntax checks Settings > Editor > Inspections > SQL
Syntax highlights Settings > Editor > Color Sheme > SQL

For multiline SQL queries, in Python, you can use triple-quote:

query = """
SELECT column1
     , column2
FROM table1
WHERE column3 IN
(
    SELECT TOP(1) column4
    FROM table2
    INNER JOIN table3
    ON table2.column1 = table3.column1
)
"""

For syntax highlight, however, since PyCharm is build for Python specifically, I don't think you can change the settings to highlight like in SQL. There may be extensions for this, however, I do not know of any.

using """ """

sql = """
        SELECT column1
     , column2
FROM table1
WHERE column3 IN
(
    SELECT TOP(1) column4
    FROM table2
    INNER JOIN table3
    ON table2.column1 = table3.column1
)
"""

print(sql)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM