How to resolve SQL table with prefix in PhpStorm? - phpstorm

I'm working on PhpStorm to develop my Prestashop websites and I can't resolve this issue. I work on localhost and successfully connected PhpStorm to my MySQL Server.
Now PhpStorm throws warnings like "unable to resolve table '${_DB_PREFIX_}cms'". Prestashop uses prefixes for table names and it seems PhpStorm can't resolve those tables with prefixes.
Is there a workaround for this ?
Here is a code exemple from Prestashop-1.6 sources :
$sql = 'SELECT c.`id_cms`, cl.`meta_title`, cl.`link_rewrite`
FROM `'._DB_PREFIX_.'cms` c
INNER JOIN `'._DB_PREFIX_.'cms_shop` cs
ON (c.`id_cms` = cs.`id_cms`)
INNER JOIN `'._DB_PREFIX_.'cms_lang` cl
ON (c.`id_cms` = cl.`id_cms`)
WHERE c.`id_cms_category` = '.(int)$id_cms_category.'
AND cs.`id_shop` = '.(int)$id_shop.'
AND cl.`id_lang` = '.(int)$id_lang.
$where_shop.'
AND c.`active` = 1
ORDER BY `position`';

The reason why this isn't work is because you are most likely only loading one schema, you need to load the information_schema.*
To do this, go to the database tab in the top right and where you have added your MySQL database right click and select properties.
Now you'll have a screen called Data Sources and Drivers, it should open on a tab called General, click the third tab called Schemas and and add information_schema.* to this list of loaded Schemas.
Click apply and okay and then PhpStorm will now know your database structure and then be intelligently able to work with you, therefor removing all the errors.

Edit: As mentioned here, this has been fixed in PhpStorm 2018.2, but only for constants.
I have a solution that doesn't involve throwing your IDE away. :)
However, a word of caution: it's an ugly hack™ that comes without guarantees.
Assuming you already have a connection to the db in PhpStorm, generate the ddl for the desired db (Right Click on the connection -> SQL Scripts -> Generate DDL to Clipboard):
Paste the content into some sql file somewhere inside your project. You should probably gitignore this file.
Replace all the tables' prefix in this ddl file with the one from your code. Use the PhpStorm typehint as a guideline. For example '._DB_PREFIX_.'cms would become ${_DB_PREFIX_}cms:
Note that you may have to use backticks to avoid breaking sql syntax due to curly brackets.
Add the ddl to your phpstorm project:
Everything should now work:

Add this comment above the $sql query.
/** #noinspection SqlResolve */
This will suppress the warning only for this statement.

For future readers, this is now supported:
https://www.jetbrains.com/help/phpstorm/2021.1/ide-advanced-metadata.html#set-up-dynamic-prefixes-for-table-names-in-sql-language-injections
.phpstorm.meta.php
<?php
namespace PHPSTORM_META {
override(
// Virtual function to indicate that all SQL
// injections will have the following replacement rules.
sql_injection_subst(),
map([
'{' => "", // all `{` in injected SQL strings will be replaced with a prefix
'}' => '', // all `}` will be replaced with an empty string
]));
}

Edit: At time of writing (2016) there was no solution to this issue. But since 2018, as mentioned in Christian's answer, you can now use constants in SQL queries.
Actually there is no way to handle that. But you may disable inspection for such warning.
Open File > Settings > Editor > Inspections
Expand SQL
Uncheck Unresolved reference

Related

Access error when saving query

I am trying to save an Access query with the following statement.
INSERT INTO FOO( DES_MOTIVO, DES_TIPO, DES_SUBTIPO,
AGRUPACIÓN, SEMANA, CuentaDeCOD_ACCION_CLIENTE )
IN 'C:\Users\BAR\Desktop\03. Hola\DB STATIC INTERACCIONES MES.accdb'
I am getting an error when saving the query, saying the path is incorrect. Testing the path, i found out that the culprit is the period+whitespace in "03. Hola". Deleting the whitespace fixed the issue and the query saves properly.
Is there a way to escape the period so that access accepts the save path with period + whitespace?
Thank you in advance,
Nega.
Apparently this is not possible with SQL or VBA code.
Fun fact: You can do it in the query designer by setting the Destination database setting of the query properties. Set your path, the query can be saved and executed (and it works!).
But switch to SQL view and try to save: you get the "invalid bracketing" error. Same when trying to set the SQL from VBA.
And the DestinationDB property that the help file mentions isn't available via code. It seems to be derived from the IN clause.
So your database will have to moved to a better path. Or, if it's single user, copy to temp path, run the INSERT, copy back.
See also: https://support.microsoft.com/en-us/kb/132184
Try adding quotes around the path:
"INSERT INTO FOO( DES_MOTIVO, DES_TIPO, DES_SUBTIPO, AGRUPACIÓN, SEMANA, CuentaDeCOD_ACCION_CLIENTE ) IN '""C:\Users\BAR\Desktop\03. Hola\DB STATIC INTERACCIONES MES.accdb""'"
But why do you maintain such weird folder names as "03. Hola"?
Indeed on the Desktop, you should be able to create a simpler folder name.

PHPStorm warnings on placeholders in WordPress plugin queries

I have a WordPress plugin that I am editing in PHPStorm. PHPStorm finds syntax errors on queries like this when the SQL dialect is set to MySQL:
$foo = $wpdb->get_var(
$wpdb->prepare(
'SELECT `foo` FROM `some_table` WHERE `id` = %d',
$bar
)
);
Specifically, it sees %d and complains with this message:
<expression> expected, got '%'
Of course, %d is a perfectly legitimate placeholder in WordPress queries. Is there a way to configure PHPStorm to accept this? Or do I have to disable all checks on SQL statements, as suggested in this answer?
Note that I am using PHPStorm EAP 8 (138.1751), and the same thing happens with other placeholders like %s.
This is now possible in PHPStorm 8, as explained by this post on the official PHPStorm blog:
Database Language Injection Configuration
To solve it:
Go to Tools > Databases
Make sure a regex matching the placeholders in question is in the list of custom parameters. By default, the list includes \%\w+, which will match %s, %d, etc.
Check the box labeled "Use in other language string literals"
PHPStorm will now correctly recognize placeholders like those used in WordPress.
Nope -- %d is not valid syntax from SQL point of view (ANY currently supported dialect). The WI-3672 and WI-2324 tickets are still valid.
But PhpStorm v8 now supports $var (if you could use it instead of % syntax) -- http://youtrack.jetbrains.com/issue/WI-2450
Since it's WordPress specific question, it's hard for me to give you any real suggestion (especially since I'm not using WordPress myself) excluding that one.
But generally speaking you could use native place holders supported by specific DB engine (check "Examples" section in http://php.net/manual/en/pdo.prepare.php):
unnamed ?
named :id
I just not sure if this can be applied to WordPress development.
P.S.
Generic is the new Keywords only dialect -- fall back to that if using proper SQL dialect shows to many warnings/errors (that are not actual errors).

How to undo sql USE?

What's the SQL command to undo:
USE db;
The syntax I see everywhere is:
USE [db] ;
implying that I can leave out the db part. Not so - this is a syntax error however (maybe just syntax errors in the SQL syntax syntax?).
edit
The programming problem this is causing is that I can't reset the environment in which subsequent commands run. I could reset my DB connection, but this seems efficient.
cmdX; // Works
vs.
cmdX;
cmdY; // May fail because command X upset some state.
cmdX should clean up after itself and put things back where it found them.
Analogously:
cd ./a
doX()
cd ../
doY() // Y expects to not be in a?
I don't think you can. The documentation doesn't say the parameter is optional. It says:
The database remains the default until the end of the session or another USE statement is issued:
So if you want to drop the default, end your session and start a new one without selecting a DB.
What programming problem is this causing for you?
The database argument is not optional.
mysql> use
ERROR:
USE must be followed by a database name
I'm not sure where you saw this command with square brackets around the argument. That is not shown at the documentation page: http://dev.mysql.com/doc/refman/5.6/en/use.html
Microsoft SQL Server uses square brackets around identifiers (as opposed to a style to indicate an optional argument), but the MS SQL documentation for USE also doesn't show it: http://msdn.microsoft.com/en-us/library/ms188366.aspx
What would it mean to "undo" a USE command? Would it be like cd - in bash, making the previous default database again the default? There is no such command in MySQL for this. It doesn't remember what was your previous default database. If you want to return, you just have to USE that database and name it explicitly.

Pasting SQL into the MySQL command line

I have an application that is defining some SQL code:
mySql = "SELECT
sq.question,
qs.title,
sq.id as question_id,
sq.type,
qs.id as option_id,
sri.title as rankTitle,
sri.id as rankId,
sfi.title as formTitle,
sfi.id as formId,
sq.sub_type,
sq.sort_order
FROM survey_questions as sq
LEFT JOIN question_suboptions as qs
ON sq.id = qs.question_id
LEFT JOIN survey_rankingitems as sri
ON sq.id = sri.question_id
LEFT JOIN survey_formitems as sfi
ON sq.id = sfi.question_id
WHERE sq.survey_id = #{#surveyId}
ORDER BY sq.sort_order"
I would like to paste this code (everything between the double quotes) in the MySQL command line, change the one parameter and execute it, but I have run into an issue where for every line above MySQL will display:
Display all 1450 possibilities? (y or n)
And then 1450 different available commands. If I remove all linebreaks and tabs then I can paste in, but that is time consuming and a pain. Is there a way that I can simply paste in the above code, edit it and then execute it as a single unit?
This is the default mysql (CLI) behavior each time the user presses the Tab key (mysql uses the underlying readline or EditLine libraries (not on Windows)).
By default, when the user requests to use a database, mysql reads tables and fields definitions. Then, pressing the Tab key makes mysql conveniently offers completion of the current input with the known tables and fields.
However, pasting some text into mysql that contains TAB characters (\t or 0x09) triggers the same behavior - even though no Tab key was actually pressed from the keyboard. And this can be annoying.
Two options given to mysql can prevent that behavior, though. My favorite is --disable-auto-rehash. The other one is --quiet or -q.
--disable-auto-rehash to prevent database, table, and column name completion (which are not read from the database, use the rehash command if later on you need completion). Commands history is kept, though (retrieved via the ↑ and ↓ keys for instance). Which is convenient.
--quick or -q which makes mysql not using the history file and no completion (does not read the database definitions).
On Linux one may add an alias in .bashrc to use --disable-auto-rehash automatically
alias mysql2='mysql --disable-auto-rehash'
Perhaps you could save the statement to a text file myTest.sql, then use the MySQL command source myTest.sql to run it? You could then tweak the SQL in the file, save the changes, and run it again.
You need to remove the line breaks and tabs. The double tab is causing it to display the Display all 1450 possibilities? (y or n) and the line breaks are causing it to execute early.
If it's PHP, write a little script to strip it for you:
echo (preg_replace("/\s+/", " ", $string));
Or something similar for other languages.
Breaking not so bad's answer explained the cause of this problem really well.
From the question:
If I remove all linebreaks and tabs then I can paste in, but that is time consuming and a pain.
In my case, I just replaced the tabs with spaces and I was able to paste the query just fine. The MySQL console doesn't seem to care about the newlines, just the tabs.
As a way to prevent this, most editors have a setting that will insert tabs instead of spaces when you press the Tab key. I normally have my IDEs configured this way, but in this instance it was a query I'd copied from MySQL workbench. Conveniently, it also has a setting to use spaces instead of tabs:
Edit > Preferences > General Editors > check Tab key inserts spaces instead of tabs > OK

Get Redmine custom field value to a file

I'm trying to create a text file that contains the value of a custom field I added on redmine. I tried to get it from an SQL query in the create method of the project_controller.rb (at line 80 on redmine 1.2.0) as follows :
sql = Mysql.new('localhost','root','pass','bitnami_redmine')
rq = sql.query("SELECT value
FROM custom_values
INNER JOIN projects
ON custom_values.customized_id=projects.id
WHERE custom_values.custom_field_id=7
AND projects.name='#{#project.name}'")
rq.each_hash { |h|
File.open('pleasework.txt', 'w') { |myfile|
myfile.write(h['value'])
}
}
sql.close
This works fine if I test it in a separate file (with an existing project name instead of #project.name) so it may be a syntax issue but I can't find what it is. I'd also be glad to hear any other solution to get that value.
Thanks !
(there's a very similar post here but none of the solutions actually worked)
First, you could use Project.connection.query instead of your own Mysql instance. Second, I would try to log the SQL RAILS_DEFAULT_LOGGER.info "SELECT ..." and check if it's ok... And the third, I would use identifier instead of name.
I ended up simply using params["project"]["custom_field_values"]["x"] where x is the custom field's id. I still don't know why the sql query didn't work but well, this is much simpler and faster.