Last active
December 13, 2019 10:10
-
-
Save anton21m/ce13275834edffedace5b3f78c8816d8 to your computer and use it in GitHub Desktop.
Creating tables and columns in mysql database only if they do not exist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Creating tables and columns in mysql database only if they do not exist | |
-- Создание таблиц и колонок в базе данных mysql только если их не существует | |
-- VARIANT 1 | |
-- Function columnExists (check column in table) | |
DROP FUNCTION IF EXISTS columnExists; | |
DELIMITER // | |
CREATE FUNCTION columnExists(t_table char(255),t_column char(255)) RETURNS boolean NOT DETERMINISTIC | |
BEGIN | |
SET @datatable := t_table, @datacolumn := t_column; | |
IF (SELECT count(*) FROM information_schema.COLUMNS WHERE COLUMN_NAME=@datacolumn AND TABLE_NAME=@datatable) THEN | |
return false; | |
ELSE | |
return true; | |
END IF; | |
END | |
// | |
DELIMITER ; | |
-- Create table newsletters | |
CREATE TABLE IF NOT EXISTS newsletters | |
(id int(11) NOT NULL AUTO_INCREMENT, | |
PRIMARY KEY (id) | |
); | |
-- Create safely columns | |
set @query = IF(columnExists('newsletters','email'), "ALTER TABLE newsletters ADD email varchar(255) NOT NULL","SELECT false"); | |
prepare stmt from @query;EXECUTE stmt; | |
set @query = IF(columnExists('newsletters','status'), "ALTER TABLE newsletters ADD status int(11) NOT NULL","SELECT false"); | |
prepare stmt from @query;EXECUTE stmt; | |
set @query = IF(columnExists('newsletters','created_at'), "ALTER TABLE newsletters ADD created_at int(11) NOT NULL","SELECT false"); | |
prepare stmt from @query;EXECUTE stmt; | |
set @query = IF(columnExists('newsletters','updated_at'), "ALTER TABLE newsletters ADD updated_at int(11) NOT NULL","SELECT false"); | |
prepare stmt from @query;EXECUTE stmt; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alternative variant
-- VARIANT 3
DROP FUNCTION IF EXISTS columnExists;
DELIMITER //
CREATE FUNCTION columnExists(t_table char(255),t_column char(255)) RETURNS boolean NOT DETERMINISTIC
BEGIN
SET @DataTable := t_table, @DataColumn := t_column;
IF (SELECT count(*) FROM information_schema.COLUMNS WHERE COLUMN_NAME=@DataColumn AND TABLE_NAME=@DataTable) THEN
return false;
ELSE
return true;
END IF;
END
//
DELIMITER ;
DROP PROCEDURE IF EXISTS upgrade_database_1_0_to_2_0;
DELIMITER
//
CREATE PROCEDURE upgrade_database_1_0_to_2_0()
BEGIN
-- add a column safely
IF (columnExists('newsletters','ida') ) THEN
ALTER TABLE newsletters ADD ida varchar(2048) NOT NULL DEFAULT '';
END IF;
END
//
DELIMITER ;
CALL upgrade_database_1_0_to_2_0();