Pasting SQL into the MySQL command line - mysql

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

Related

How to resolve SQL table with prefix in 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

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.

Access 2010 String Comparison Invalid procedure call

We've just upgraded from Access 2003 to Access 2010 and string comparisons are failing with an invalid procedure call error when default conditions are used. I’ve recreated two presumably related problems in a new Access 2007 format database containing only the default table, a query with the SQL below and a module containing only the code below, so I seriously doubt that this is a corruption issue.
First the following sub fails on the If Then line with Run-time error 5: Invalid procedure call or argument
Option Compare Database
Option Explicit
Sub checkStrCmp()
Dim str As String
str = "s"
If str = "s" Then
MsgBox "works"
End If
End Sub
If I change Option Compare Database to Option Compare Text the sub works as expected, but this seems like a bad idea as I may want to preform text as well as numeric comparisons inside a single sub.
I’m also getting “Invalid procedure call” errors in string comparison functions inside of SQL. The Replace function is requiring the supposedly optional compare parameter.
Select replace("foo-bar-baz", "-", "|", 1,-1);
Generates the “Invalid procedure call” error
Setting the compare parameter to any of the available values (0 -3) works as expected:
SELECT replace("foo-bar-baz", "-", "|", 1,-1, 0);
produces “foo|bar|baz”
Has anyone else seen this? Is there a setting that needs to be tweaked? Any other ideas outside of “Database corruption” which is all I’ve been able to find via Google.
TIA
apoligies for the sloppy code blocks I can't for the life of me get them to work right.
UPDATE: I should have mentioned that I'm running XP Pro sp3.
The problem seems limited to databases I create on my box. When I opened the test database I created on my box from other workstations on our network I saw the issue, but was then unable to recreate it when creating a new database as described above on those workstations. The databases I created on the two other workstations (same OS and MS Office versions installed) also worked correctly when opened on my machine. I was also unable to recreate the issue when I inserted new modules in those DBs from my machine.
In short the problem seems to only exist on databases created on my machine (and in old 2003 format databases I've converted to 2007 format on my machine). My best guess is that my install is hosed but I’d like to have some idea of how and why before I approach IT with a request to reinstall Office. I’d also like to rule out a conflict with other software on my box.
Your code modules do not all need to share the same Option Compare setting. So you could place those procedures which should use text comparisons in a module which has Option Compare Text in its Declarations section.
However, I don't understand your statement, "I may want to preform text as well as numeric comparisons inside a single sub." According to Access' help topic, the Option Compare Statement is "Used at module level to declare the default comparison method to use when string data is compared". In other words, Option Compare has no effect on the comparisons of numeric values.
Edit: Since the problem is limited to Option Compare Database for database files created on only one machine, I'll suggest you check Access' "New database sort order" setting on that machine. Change it to a choice which starts with "General" if it is set to anything else. Then create a new database and see whether you still have the problem.
The reason for this suggestion is that Option Compare Database tells Access to use the database's codepage setting for sorting. And "New database sort order" can set the codepage to the one which never gives me such troubles. However, my understanding of codepage details is pretty shallow; I never change it and don't know what the consequences of other settings would be.

How to disable or circumvent phpmyadmin's SQL_CALC_FOUND_ROWS

When you process a SELECT through phpmyadmin, behind the scenes, it will sometimes add a LIMIT 0,30, and/or it'll throw a SQL_CALC_FOUND_ROWS into the SELECT so it can tell me how many results there would have been without the LIMIT.
Unfortunately, adding the SQL_CALC_FOUND_ROWS sometimes requires much more processing than I was expecting (i.e. more than if I had ran my original untainted query).
Is there a global config option to disable phpmyadmin's modification(s) of my queries?
What tricks can I use on a per-query basis to prevent phpmyadmin's modification(s)?
A quick check of the PHPMyAdmin source code says there isn't one.
However, if you look in the file sql.php, and find the else statement labelled // n o t " j u s t b r o w s i n g ". Replace the code between there and // end else "just browsing" with something like $unlim_num_rows = 1000000; you'll prevent it doing its counting query, while still being able to browse.
(you'll have to repeat this each time you update PMA, which you should be doing regularly since its security reputation is not great, to say the least)

Executing Line/Multiple Lines Only in mySQL Query Browser

I already used Microsoft SQL Server 2005 and found really easy to execute single/multiple lines of an sql query.
Example:
insert into tablea
($vala, $valb, $valc)
values
($vala, $valb, $valc);
insert into tableb
($vala, $valb, $valc)
values
($vala, $valb, $valc);
How can I execute the second part only? In MSSQL i will highlight the second insert statment and press F5. How can do this in mySQL?
The problem is that you must be trying to execute your query from a Query Tab rather than from a Script Tab. Go to File -> New Script Tab and input your multiple statements there. Next click the execute button... that's it.
Hope it helps!
Machi
You can do this. When you have logged into MySQL query browser, and you write two complete statments such as:
select "hello world";
select "second query";
You will notice two blue dots on the left side of the window they are left of the line numbers. By default it will try to exec the first command. That might be why you see one command with white background and all the others with a grey background. The command that is white, is highlighted and it is the one that will be executed. You should be able to just click anywhere inside the second query to highlight it and then click the lightning bolt button (execute) to run it.
You can do this in MySQL, but you have to use mysqli. Click here for details:
http://php.net/manual/en/mysqli.quickstart.multiple-statement.php
In workbench, make sure the cursor is in the statement you want to execute and hit Ctrl+Enter.
Ctrl+Shift+Enter will run all statements consecutively in the window/document.
In addition if you have selected a statement, Ctrl+Shift+Enter will execute the selected statement only.
Does selecting the second part and "EXECUTE" help? If not, then I am not sure if such a use case is supported. You might want to try MySQL Workbench though.
well the issue here is that if i write the queries :
select "hello world";
select "second query";
and Execute it gives error -- when i select/highlight any one of them and execute it gives the same error -- so i have to either delete one of the queries or comment it out or use the script editor which doesn't work for me and lot of other users who have use MS SQL 2000,2005.
If there a solution for this -- ideally it should execute the query i select .
Just an opinion
Rohan