Flyway | MariaDb - Unable to execute conditional block - mysql

I want to add a not null column to a table with existing data. My toolset includes MariaDb and flyway. Here's what I am doing
IF NOT EXISTS(SELECT 1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'MY_DATA_TABLE'
AND table_schema = '${schemaName}'
AND column_name = 'NewColumnName'
) THEN
ALTER TABLE MY_DATA_TABLE ADD COLUMN 'NewColumnName' INT;
SELECT ID INTO #val FROM MASTER_TABLE WHERE lower(Name) = 'XYZ';
UPDATE MY_DATA_TABLE SET NewColumnName = #val;
ALTER TABLE MY_DATA_TABLE MODIFY COLUMN 'NewColumnName' INT NOT NULL;
END IF;
Doing mvn flyway:migrate gives me this error
[ERROR] SQL State : 42000
[ERROR] Error Code : 1064
[ERROR] Message : You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''NewColumnName'
INT' at line 7
I even tried placing some running select statement inside, but the error remains the same. Please suggest some workaround. Please also recommend if there's another way to achieve the objective.
Thanks!

I suspect the issue is with quoting the column name. Try executing the SQL interactively and see if you get the same error. Then try and get it working successfully. In a related question the answer was to try no quotes around column names or to escape them with back ticks.

Here's how I ended up to meet the desired.
DROP PROCEDURE IF EXISTS `proc_UpdateMyColumn`;
DELIMITER //
CREATE PROCEDURE `proc_UpdateMyColumn`
(
)
BEGIN
DECLARE valueToSet INT;
IF NOT EXISTS (SELECT 1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'MY_DATA_TABLE'
AND table_schema = '${schemaName}'
AND column_name = 'NewColumnName'
) THEN
ALTER TABLE MY_DATA_TABLE ADD COLUMN NewColumnName INT;
SELECT ID INTO valueToSet FROM MASTER_TABLE WHERE lower(Name) = 'XYZ';
UPDATE MY_DATA_TABLE SET NewColumnName = valueToSet;
ALTER TABLE MY_DATA_TABLE MODIFY COLUMN NewColumnName INT NOT NULL;
END IF;
END;
DELIMITER;
CALL `proc_UpdateMyColumn`();
DELIMITER;

Related

create function throws error in mysql,can someone help me out?

I am just trying to create a function which means to check if a table,function or view exists in a mysql database. But I get some errors in my database. Can someone help me out?
DELIMITER $$
DROP FUNCTION IF EXISTS check_if_exists$$
CREATE FUNCTION check_if_exists
(
object_name VARCHAR(100),
db_name VARCHAR(100),
object_type ENUM('t', 'f', 'v', 'p')
)
RETURNS INT
BEGIN
IF (object_type='t') THEN
SELECT COUNT(1) INTO #f_result
from information_schema.TABLES as t1
where t1.TABLE_SCHEMA=db_name
and t1.TABLE_NAME=object_name;
ELSE IF (object_type='f') THEN
select count(1) INTO #f_result
FROM information_schema.ROUTINES as info
WHERE info.ROUTINE_SCHEMA = db_name
AND info.ROUTINE_TYPE = 'FUNCTION' AND info.ROUTINE_NAME = object_name;
ELSE IF (object_type='v') THEN
select count(1) into #f_result
from information_schema.VIEWS as t1
where t1.TABLE_SCHEMA=db_name and t1.TABLE_NAME=object_name;
ELSE IF (object_type='p') THEN
SELECT COUNT(1) INTO #f_result
FROM information_schema.ROUTINES as info
WHERE info.ROUTINE_SCHEMA = db_name
AND info.ROUTINE_TYPE = 'PROCEDURE'
AND info.ROUTINE_NAME = object_name;
END IF;
return (#f_result);
END$$
delimiter ;
another thing, the info of mysql:
mysql Ver 14.14 Distrib 5.5.37, for Linux (x86_64) using readline 5.1
and the error message is:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 31
as you see, the error message is not helpful. This definition of function do not depend any user database. So you can try in your own DBMS.
You start four IF statements, but you only have one END IF at the end.
The error message about syntax error near '' indicates that it parsed to the end of the statement, expected to find more syntax (like the balancing END IF for the remaining nested IF statements), and didn't find it. The syntax error tries to give you context by showing you what text exists in the remaining part of the statement after the error, but if it reaches the end before it discovers the error, then there is no following text to report.
You might consider using the CASE statement instead:
DELIMITER $$
DROP FUNCTION IF EXISTS check_if_exists$$
CREATE FUNCTION check_if_exists (
object_name VARCHAR(100),
db_name VARCHAR(100),
object_type ENUM('t', 'f', 'v', 'p')
)
RETURNS INT
READS SQL DATA
BEGIN
DECLARE f_result INT DEFAULT 0;
CASE object_type
WHEN 't' THEN
SELECT COUNT(1) INTO f_result
FROM information_schema.TABLES AS t1
WHERE t1.TABLE_SCHEMA = db_name
AND t1.TABLE_NAME = object_name;
WHEN 'f' THEN
SELECT COUNT(1) INTO f_result
FROM information_schema.ROUTINES AS info
WHERE info.ROUTINE_SCHEMA = db_name
AND info.ROUTINE_TYPE = 'FUNCTION'
AND info.ROUTINE_NAME = object_name;
WHEN 'v' THEN
SELECT COUNT(1) INTO f_result
FROM information_schema.VIEWS AS t1
WHERE t1.TABLE_SCHEMA = db_name
AND t1.TABLE_NAME = object_name;
WHEN 'p' THEN
SELECT COUNT(1) INTO f_result
FROM information_schema.ROUTINES as info
WHERE info.ROUTINE_SCHEMA = db_name
AND info.ROUTINE_TYPE = 'PROCEDURE'
AND info.ROUTINE_NAME = object_name;
END CASE;
RETURN (f_result);
END$$
DELIMITER ;
Re your comment:
I am trying to use if...else if...else like any other language. There is no else if in mysql?
Not in the way you were using. There is no "ladder" possible with an indefinite number of else-if clauses in standard SQL.
But many languages allow the else block to contain another if/then/else statement. So you can make complex branching code. But you have to terminate each if/then/else statement properly.
IF ... THEN /* start 1st statement */
ELSE
IF ... THEN /* start 2nd statement */
ELSE
IF ... THEN /* start 3rd statement */
ELSE
END IF /* end 3rd statement */
END IF /* end 2nd statement */
END IF /* end 1st statement */
Languages that permit ladders:
Perl (elsif)
Ruby (elsif)
PHP (elseif)
Python (elif)
BASIC (elseif)
PL/SQL (elsif)
PL/pgSQL (elsif)
F# (elif)
Languages that do not permit ladders, but do permit nested control structures:
C
C++
C#
Objective-C
Java
Javascript
ANSI SQL, Transact-SQL
Pascal, Delphi
Awk
Scala
Haskell
R
Swift
Dart
Go

How to make MySQL produce an error if value not specified on NOT NULL Columns?

Let's assume that I have a NOT NULL column in a table,
How can I make MySQL to produce an error if such statement is used?
INSERT INTO tableName () VALUES ();
Thank you.
To set a column to not null use this syntax :
ALTER TABLE table_name
MODIFY column_name [data type] NOT NULL;
If you column is declared not null an error will be produced !!
If you want a customized error msg then you need to create trigger action !
Here is a trigger that can help you :
DELIMITER $$
CREATE TRIGGER trgBEFORE UPDATE ON `tbl`
FOR EACH ROW BEGIN
declare msg varchar(255);
IF (NEW.col1IS NULL ) THEN
set msg = concat('MyTriggerError: Trying to insert a null value );
signal sqlstate '45000' set message_text = msg;
ELSE
SET NEW.col1= NEW.col1);
END IF;
END$$
DELIMITER ;
I know this is late but it might help someone.
You can set the SQL mode, either in the configuration file or at runtime for current session.
To produce the error you need to enable strict sql mode with:
SET GLOBAL sql_mode = 'STRICT_ALL_TABLES'; or SET GLOBAL sql_mode = 'STRICT_TRANS_TABLES';
Here is a link for more information on sql modes.
How to make MySQL produce an error, when inserting a row to a table containing NOT NULL column, when not specifying a value to that column like in "INSERT INTO tableName () VALUES()".
Is there a way without a trigger?
This is possible without a trigger only when you define no default when defining a column. Also the same is applicable for alter ... column ...
Example 1:
create table ck_nn( i int not null );
insert into ck_nn values();
The above insert throws an error as no default is defined on the column.
Message can be something like Field 'i' doesn't have a default value.
Example 2:
create table ck_nn2( i2 int not null default 999 );
insert into ck_nn2 values();
The above insert won't throw any error as default value is defined on the column.
select * from ck_nn2;
+-----+
| i2 |
+-----+
| 999 |
+-----+
Example # SQL Fiddle

parameters sql query inside of a stored procedure mysql

I'm working with stored procedures in mysql, so I have the following procedure:
DELIMITER ##
DROP PROCEDURE IF EXISTS generarEstadisticoRD ##
CREATE PROCEDURE generarEstadisticoRD ( mesInicial INT,anualInicial INT, mesFinal INT,anualFinal INT, codigoEntidad CHAR(3),mes INT )
BEGIN
DECLARE controlador INT;
DECLARE tipoDocumento CHAR(2);
DECLARE cursorDocumentos CURSOR FOR SELECT DISTINCT e.claseDocIdentidadFallecido
FROM EstadisticoRD e WHERE e.anual>=anualInicial AND e.anual<=anualFinal
AND e.mes >=mesInicial AND e.mes<=mesFinal AND e.codOficina=codigoEntidad;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET controlador = 1;
DROP TEMPORARY TABLE IF EXISTS estadistico;
CREATE TEMPORARY TABLE IF NOT EXISTS
estadistico( TIPO CHAR(2), MES INT );
OPEN cursorDocumentos;
cursorLoop : LOOP
FETCH cursorDocumentos INTO tipoDocumento;
IF( controlador=1 ) THEN
LEAVE cursorLoop;
END IF
/**
*Lógica
*/
INSERT INTO estadistico(`TIPO`,`MES`)
SELECT DISTINCT
c.descripcion,
IFNULL( (SELECT e.numRegistrosReportados FROM estadisticoRD e WHERE e.codOficina=codigoEntidad
AND e.claseDocIdentidadFallecido=tipoDocumento AND e.mes=mes ), 0)
FROM estadisticoRD e, claseDoc c WHERE e.codOficina=codigoEntidad AND e.claseDocIdentidadFallecido=tipoDocumento
AND c.claseDoc = e.claseDocIdentidadFallecido;
END LOOP cursorLoop;
CLOSE cursorDocumentos;
SELECT * FROM estadistico;
END ##
DELIMITER ;
I get the following messages when I try to execute the procedure:
Executed successfully in 0,001 s, 0 rows affected.
Line 2, column 1
Error code 1064, SQL state 42000: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO estadistico(`TIPO`,`MES`)
SELECT DISTINCT c.descripcion,
' at line 24
Line 3, column 1
So, what am I doing wrong?.
UPDATE 1:
The I corrected the mistake with semicolon thanks #Daniel Victoria
But now I get the following mistake:
Error code 1267, SQL state HY000: Illegal mix of collations (latin1_spanish_ci,IMPLICIT) and (latin1_swedish_ci,IMPLICIT) for operation '='
Exactly I get this mistake when I do
SELECT DISTINCT e.claseDocIdentidadFallecido
FROM EstadisticoRD e WHERE ... AND e.codOficina=codigoEntidad;
why when I do e.codOficina=codigoEntidad I get this mistake, how to fixed it?.
UPDATE 2:
To solve it, I need to put COLLATE latin1_swedish_ci after to the column that has the mistake.
In this case the new query is :
SELECT DISTINCT *
FROM estadisticoRD e WHERE e.anual>=anualInicial AND e.anual<=anualFinal
AND e.mes >=mesInicial AND e.mes<=mesFinal AND e.codOficina = codigoEntidad COLLATE latin1_swedish_ci;
I hope to finish this procedure the best way.
Your are missing a semicolon (;) after the "END IF"

MySQL Derterministic migration script

I am currently looking a way to have my database under version control. To achieve so, I wanted to have deterministic procedures that can only be run only once (with corresponding undo).
I have a problem building my first script which is riddled with small bugs.
Here are the 3 main parts :
Condition to execute query (if field doesn't exists)
SELECT *
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'my_database'
AND TABLE_NAME = 'my_table'
AND COLUMN_NAME = 'full_name'
The table alteration:
ALTER TABLE
my_table
ADD full_name VARCHAR(255) NOT NULL;
And finally the data migration
UPDATE candidat dest JOIN candidat src ON dest.id = src.id
SET dest.full_name = CONCAT(src.first_name, ' ', IF(src.middle_name='', '', CONCAT(src.middle_name, ' ')), src.last_name);
I'am trying to make this work in this form:
DELIMITER $$
DROP PROCEDURE IF EXISTS migration_001;
CREATE PROCEDURE migration_001()
BEGIN
IF NOT EXISTS (
SELECT *
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'my_database'
AND TABLE_NAME = 'my_table'
AND COLUMN_NAME = 'full_name')
THEN
ALTER TABLE
my_table
ADD full_name VARCHAR(255) NOT NULL;
UPDATE candidat dest JOIN candidat src ON dest.id = src.id
SET dest.full_name = CONCAT(src.first_name, ' ', IF(src.middle_name='', '', CONCAT(src.middle_name, ' ')), src.last_name);
END IF
END;
$$
Current error I am getting:
1064 : ... right syntax to use near 'CREATE PROCEDURE migration_001() BEGIN IF NOT EXISTS ( SELECT * ' at line 3
Can anyone point me in the right direction for solving this?
BTW I am using 5.5.16-log - MySQL Community Server.
Change the order of
DELIMITER $$
and
DROP PROCEDURE IF EXISTS migration_001;
Currently you are using the wrong delimiter to drop the procedure.

Use MySql function variables as table name in the query

I need to have a function that increments the certain ID in a table (like auto_increment)
I have smth like this
DELIMITER $$
DROP FUNCTION IF EXISTS `GetNextID`$$
CREATE FUNCTION `GetNextID`(tblName TEXT, increment INT)
RETURNS INT
DETERMINISTIC
BEGIN
DECLARE NextID INT;
SELECT MAX(concat(tblName, 'ID')) + increment INTO NextID FROM concat('table_', tblName);
## SELECT MAX(articleID) + increment INTO NextID FROM table_article;
RETURN NextID;
END$$
DELIMITER ;
INSERT INTO `table_article` ( articleID, articleAlias ) VALUES ( GetNextID('article', 5), 'TEST' );
So i pass two variables: tblName (without table_ prefix), and the increment number. The commented line - SELECT query inside the function itself - works well, but i want to dynamically pass table name to the function and so get data from a certain col of certain table. What am I doing wrong?
The error is:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '('table_', tblName);
RETURN NextID;
END' at line 6
if i simply try to select max value in such a way
SELECT MAX(articleID) + increment INTO NextID FROM tblName;
The error reports that tblName does not exist. How can i tell MySql that this is actually a var passed to the function, not an exact table name? If it is possible.
you need something like
prepare stmp from concat('SELECT MAX(ID) + ', increment, ' INTO NextID FROM table_', tblName);
execute stmp;
deallocate prepare stmp;