Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get PhpStorm to understand different SQL dialects in HEREDOC in the same project

My PHP 7.3 application connects to MS SQL Server or MariaDB, depending on being run under Windows or Linux.

For my queries, I sometimes write queries in SQL Server syntax and sometimes in MySQL syntax. For code validation etc. I use PhpStorm's language injection via HEREDOC

Of course, only the dialect that is configured in the project, is validated correctly.

Example:

switch ($dt_type) {
    case 'MSSQL':
        $sql_string = <<<SQL
            [MSSQL query here]
        SQL;
    case 'MYSQL':
    case 'MSSQL':
        $sql_string = <<<SQL
            [MYSQL query here]
        SQL;
}

I configured the MSSQL dialect in my project, so PhpStorm (correctly, expectedly) marks my MySQL queries as invalid and quirks the syntax highlighting.

Is there a way to tell PhpStorm, that a specific string should be validated with a different SQL dialect, for example by declaring it in a comment just before that string declaration? I tried the @lang annotation, and language injection comments.. without any success.

I am aware it might not be possible, but maybe someone knows a trick?

like image 810
jasie Avatar asked Mar 04 '23 10:03

jasie


1 Answers

SQL is used to apply the current SQL Dialect for that file (in case if you do not know: you can configure the IDE to have different dialects on per file/folder basis).

enter image description here


To have two dialects in the same file:

  1. Do not use SQL as an identifier if you will be changing it across the project (as it will use current SQL Dialect for that file).

    I mean: you can use it, not an issue; but do not get lost/confused if you change the dialect later for that folder/file or for the whole project.

  2. Create and use more specific identifiers instead that will instruct the IDE to use a specific dialect there.

It's easy: just clone and adjust a bit a Language Injection rule for the bundled SQL identifier:

  1. Settings (Preferences on macOS) | Editor | Language Injections

  2. Clone existing rule for <<<SQL and adjust as needed (or create new one from scratch using the right type)

enter image description here

As you may see from this example, string for PostgreSQL complains on syntax (there is no DB attached to the project, hence unknown table table):

enter image description here


In-place language injection via @lang also works. NOTE that the injection must be placed just before the string content, not before the variable etc.

$sql1 = /** @lang MySQL */'SELECT * FROM `table`';
$sql2 = /** @lang PostgreSQL */'SELECT * FROM `table`';

enter image description here

like image 52
LazyOne Avatar answered Mar 06 '23 00:03

LazyOne