How do I make PyCharm recognize placeholders in SQL statements?
Asked Answered
M

2

20

I'm using PyCharm and I have an error on this SQL statement:

SELECT * FROM table WHERE id= %(id)s

The code syntax inspection says:

<expression> expected, got '%'

Is there a way to disable this error message? In other words, how do I make PyCharm recognize placeholders in SQL statements?

Edit

Here is my solution:

For %(id)s and %s you have to had %\((\w+)\)s and %s in Settings/Preferences | Tools | Database | User parameters and select All languages not only SQL

Martynne answered 18/3, 2016 at 11:14 Comment(4)
Settings/Preferences | Tools | Database | User parameters -- you can add custom parameter pattern there. Also make sure that appropriate Enable ... options are enabled.Marola
Thanks ! I tried this pattern but it doesn't work : \%\(([^$\(\)]*)\)\s Do you have an idea please?Martynne
I think those brackets () in actual placeholder %(id)s are what making it break. I've tried few things and none of them worked. Right now I may only suggest to submit official support ticket at intellij-support.jetbrains.com/hc/en-us/requests/newMarola
%\(([^\$\(\)]*)\)s does work in the one test case I've tried so far. Most of my code base uses %s so I've also added that as a pattern.Interspace
B
23

Is this SQL in a SQL console, or in a string in a Python script? I had this same issue and solved it by checking the box above the list of patterns, labeled "Enable in string literals with SQL injection". If you're doing this in a SQL console window, check the first box.

As @LazyOne notes, go to Settings/Preferences > Tools > Database > User Parameters and you'll see two checkboxes at the top:
Enable in console and SQL files
Enable in string literals with SQL injection

While you can add your own custom patters, I believe the pattern that matches this parameter syntax (for me, parameters for psycopg2 for use in Postgres) is out-of-the-box in Pycharm, the last one in the list.

See here for reference:
https://www.jetbrains.com/help/pycharm/2016.1/user-parameters.html

Begird answered 1/4, 2016 at 1:44 Comment(0)
I
0

In addition to @Nate's answer (built-in regex %\((\w+)\)s works for PostgreSQL), i've managed to get this work only via reordering the patterns and moving target regex to the top of the list.

One could also try to disable other rules and see if that helps.

Inhumane answered 26/8, 2016 at 15:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.