Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for adding a column if it doesn't exist #331

Open
ScottPierce opened this issue Feb 27, 2022 · 3 comments
Open

Support for adding a column if it doesn't exist #331

ScottPierce opened this issue Feb 27, 2022 · 3 comments
Labels

Comments

@ScottPierce
Copy link

Dialect

MySQL

Failing SQL

SELECT count(*) INTO @EXIST
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'mydatabase'
  AND COLUMN_NAME = 'mycolumn'
  AND TABLE_NAME = 'mytable' LIMIT 1;

SET @query = IF (@exist <= 0, 'ALTER TABLE mydatabase.`mytable`  ADD COLUMN `mycolumn` MEDIUMTEXT NULL',
    'select \' COLUMN EXISTS\' status');
PREPARE stmt FROM @query;
EXECUTE stmt;

Description

I'm trying to write my migration files in a repeatable manner (So I don't have to create a new migration version EVERY time I need to make a change), but I can't seem to do this when altering a table when adding a column or adding an index. I don't necessarily need to do it in the above way, but I do think this should be supported some way.

@ScottPierce
Copy link
Author

Ran into the desire to do this again:

IF NOT EXISTS( SELECT NULL
            FROM INFORMATION_SCHEMA.COLUMNS
           WHERE table_name = 'tableName'
             AND table_schema = 'database_name'
             AND column_name = 'columnName')  THEN
 
  ALTER TABLE Example ADD COLUMN location VARCHAR(50) NULL;
 
END IF;

@AlecKazakova
Copy link
Collaborator

is that valid MySQL? thats nutts if you can just do if statements

@ScottPierce
Copy link
Author

I'll be honest, I'm no mysql expert. I'm trying to find a way to make my migrations idempotent so that they can be re-run. every time there is a change. I took the syntax from here: https://www.w3schools.blog/alter-table-if-column-not-exist-in-mysql

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants