sqitch...-mysql(3pm)

๐Ÿ’– sqitchtutorial-mysql โ€” A Tutorial Introduction to Sqitch Change Management on MySQL ๐Ÿ’–

okay bestie, welcome to sqitchtutorial-mysql from the User Contributed Perl Documentation โœจ grab a snack, we're doing this ๐Ÿซถ


โœจ Name โœจ

sqitchtutorial-mysql โ€” a tutorial introduction to Sqitch change management on MySQL ๐Ÿ’…


โœจ Synopsis โœจ

sqitch *

โœจ Description โœจ

So this tutorial walks you through making a Sqitch-enabled MySQL 5.7 project from the ground up, using a VCS for deployment planning, and teaming up with other devs so everybody's changes stay in sync and in the right order. No cap ๐Ÿ”ฅ

We're starting a whole new project from scratch โ€” a fictional antisocial networking site called Flipr. Every single example uses Git (https://git-scm.com/) as the VCS and MySQL (https://dev.mysql.com/) as the storage engine. ๐Ÿ˜Œ

If you wanna manage a database with a different database engine instead, go check out one of these other tutorials:

  • PostgreSQL, Yugabyte, and CockroachDB Tutorial
  • SQLite Tutorial
  • Oracle Tutorial
  • Firebird Tutorial
  • Vertica Tutorial
  • Exasol Tutorial
  • Snowflake Tutorial
  • ClickHouse Tutorial

๐ŸŽ€ Starting a New Project ๐ŸŽ€

Bestie, usually the very first thing you do when you start a new project is make a source code repository. So that's what we're doing, with Git:

> mkdir flipr
> cd flipr
> git init .
Initialized empty Git repository in /flipr/.git/
> touch README.md
> git add .
> git commit -am 'Initialize project, add README.'
[main (root-commit) fdf2a40] Initialize project, add README.
 1 file changed, 38 insertions(+)
 create mode 100644 README.md

If you're a Git girlie and wanna follow along with the history, the repository used in these examples lives on GitHub (https://github.com/sqitchers/sqitch-mysql-intro). ๐ŸŒธ

Now that we've got a repo, let's get into Sqitch. Every Sqitch project has to have a name attached to it, and optionally a unique URI. We really recommend including the URI, because it bumps up the uniqueness of object identifiers internally, and it stops a totally different project with the same name from deploying. So let's specify one when we initialize Sqitch:

> sqitch init flipr --uri https://github.com/sqitchers/sqitch-mysql-intro/ --engine mysql
Created sqitch.conf
Created sqitch.plan
Created deploy/
Created revert/
Created verify/

Let's peek at sqitch.conf:

> cat sqitch.conf
[core]
        engine = mysql
        # plan_file = sqitch.plan
        # top_dir = .
# [engine "mysql"]
        # target = db:mysql:
        # registry = sqitch
        # client = mysql

Obsessed ๐Ÿ˜ญ it clocked that we're creating changes for the MySQL engine, all thanks to the --engine mysql option, and saved it to the file. And on top of that, it wrote a commented-out [engine "mysql"] section with every single available MySQL engine-specific setting commented out and ready for you to edit however you need. ๐Ÿ’…

By default, Sqitch reads sqitch.conf in the current directory for settings. But it also reads ~/.sqitch/sqitch.conf for user-specific settings. Since MySQL's mysql client (https://dev.mysql.com/doc/refman/5.7/en/mysql.html) is not in the path on my system, let's go ahead and tell it where to find the client on our computer โ€” don't even bother if you're using the Docker image (https://hub.docker.com/r/sqitch/sqitch/) because it uses the client inside the container, not on your host machine:

> sqitch config --user engine.mysql.client /usr/local/mysql/bin/mysql

And let's also tell it who we are, since this data gets used in all of our projects:

> sqitch config --user user.name 'Marge N. Oโ€™Vera'
> sqitch config --user user.email 'marge@example.com'

Have a look at ~/.sqitch/sqitch.conf and you'll see this:

> cat ~/.sqitch/sqitch.conf
[engine "mysql"]
        client = /usr/local/mysql/bin/mysql
[user]
        name = Marge N. Oโ€™Vera
        email = marge@example.com

Which means Sqitch should be able to find mysql for any project, and it will always properly identify us when planning and committing changes. ๐Ÿ‘‘

Back to the repository. Have a look at the plan file, sqitch.plan:

> cat sqitch.plan
%syntax-version=1.0.0
%project=flipr
%uri=https://github.com/sqitchers/sqitch-mysql-intro/

Note that it picked up on the name and URI of the app we're building. Sqitch uses this data to manage cross-project dependencies. The %syntax-version pragma is always set by Sqitch, so that it always knows how to parse the plan, even if the format changes in the future. iykyk โœจ

Let's commit these changes and start creating the database changes.

> git add .
> git commit -am 'Initialize Sqitch configuration.'
[main 79fe2cc] Initialize Sqitch configuration.
 2 files changed, 19 insertions(+)
 create mode 100644 sqitch.conf
 create mode 100644 sqitch.plan

๐Ÿ’– Our First Change ๐Ÿ’–

okay so first thing, bestie: our app needs a database user. Let's make one. Run this:

> sqitch add appuser -n 'Creates a an application user.'
Created deploy/appuser.sql
Created revert/appuser.sql
Created verify/appuser.sql
Added "appuser" to sqitch.plan

The add command adds a database change to the plan and writes out deploy, revert, and verify scripts to represent that change. Now we edit those files. โœจ

The deploy script is the one that actually makes the thing happen. By default, the deploy/appuser.sql file looks like this:

-- Deploy flipr:appuser to mysql

BEGIN;

-- XXX Add DDLs here.

COMMIT;

What we want to do is swap that XXX comment out for a CREATE USER statement, like so:

-- Deploy flipr:users to mysql

BEGIN;

CREATE USER flipr;

COMMIT;

The revert script's whole job is to precisely undo whatever the deploy script did, so we edit revert/appuser.sql to look like this:

-- Revert flipr:users from mysql

BEGIN;

DROP USER flipr;

COMMIT;

Now we can actually try deploying this change. First we need a database to deploy to:

> mysql -u root --execute 'CREATE DATABASE flipr_test'

Now we tell Sqitch where to send the change, via a database URI <https://github.com/libwww-perl/uri-db/>:

> sqitch deploy db:mysql://root@/flipr_test
Deploying changes to db:mysql://root@/flipr_test
  + appuser .. ok

First, Sqitch created the registry database and the tables it uses to track database changes. Heads up: that registry database is separate from the database the appuser change got deployed to. By default its name is sqitch, and it'll be used to manage all the projects on a single MySQL server. Ideally only Sqitch data lives in there, so honestly it probably makes the most sense to create a superuser named sqitch (or something similar) and use that to deploy changes. ๐Ÿ’…

If you'd rather use a different database as the registry database, use sqitch engine add mysql $name to configure it (or the target command โ€” more on that below). That's handy when you don't want the same registry database managing multiple databases on the same server.

Next, Sqitch deploys the changes to the target database, the one we specified on the command line. We've only got one change so far, and that little + reinforces the idea that the change is being added to the database. ๐Ÿ‘‘

With this change deployed, if you connect to the database you'll be able to see the user:

> mysql -u root --execute "SELECT user from mysql.user WHERE user = 'flipr';"
+-------+
| User  |
+-------+
| flipr |
+-------+

๐Ÿฆ‹ Trust, But Verify ๐Ÿฆ‹

But bestie. That's so much work. Do you really want to be doing all that after every single deploy? No. Absolutely not.

This is where the verify script comes in. Its job is to test that the deploy actually did what it was supposed to. It should do that without caring about any data that might be in the database, and it should throw an error if the deploy wasn't successful. The simplest way to check whether a user exists is to look at the mysql.user table. However, throwing an error when the user doesn't exist is genuinely tricky in MySQL.

To keep it simple, on MySQL 5.5.0 and higher, Sqitch gives you a custom function you can use in your tests: checkit(). It works kind of like a CHECK constraint in other databases โ€” you pass an expression as the first argument, and an error message as the second. If the expression evaluates to false, an exception gets thrown with your error message. ๐Ÿ˜Œ

Give it a try. Put this query into verify/appuser.sql:

SELECT sqitch.checkit(COUNT(*), 'User "flipr" does not exist')
  FROM mysql.user WHERE user = 'flipr';

This will work great as long as we know the registry database is named sqitch. If you've set engine.mysql.registry to a different value, you'll need to make sure you specify the correct database name in the script.

In some configurations, Sqitch does not include checkit(). You can add it by connecting to the sqitch registry database as a super user and running:

DELIMITER |
CREATE FUNCTION checkit(doit INTEGER, message VARCHAR(256)) RETURNS INTEGER DETERMINISTIC
BEGIN
    IF doit IS NULL OR doit = 0 THEN
        SIGNAL SQLSTATE 'ERR0R' SET MESSAGE_TEXT = message;
    END IF;
    RETURN doit;
END;
|

Now you can run the verify script with the verify command:

> sqitch verify db:mysql://root@/flipr_test
Verifying flipr_test
  * appuser .. ok
Verify successful

Looks good! ๐Ÿ˜ And if you wanna make sure the verify script actually dies when the user doesn't exist, temporarily change the user name in the script to something that doesn't exist, something like:

SELECT sqitch.checkit(COUNT(*), 'User "flipr" does not exist')
  FROM mysql.user WHERE user = 'nonesuch';

Then verify again:

> sqitch verify db:mysql://root@/flipr_test
Verifying db:mysql://root@/flipr_test
  * appuser .. ERROR 1644 (ERR0R) at line 5 in file: 'verify/appuser.sql': User "flipr" does not exist
# Verify script "verify/appuser.sql" failed.
not ok

Verify Summary Report
---------------------
Changes: 1
Errors:  1
Verify failed

The checkit() function is kind enough to use the error message to tell us exactly what the problem is. ๐Ÿซถ And don't forget to change the table name back before continuing!

๐ŸŒธ Status, Revert, Log, Repeat ๐ŸŒธ

For purely informational purposes, we can always see how a deployment got recorded via the status command, which reads the tables from the registry database:

> sqitch status db:mysql://root@/flipr_test
# On database db:mysql://root@/flipr_test
# Project:  flipr
# Change:   f56dd1a1ab029f398cec2cebb2ecc527fa0332c2
# Name:     appuser
# Deployed: 2013-12-31 13:13:17 -0800
# By:       Marge N. Oโ€™Vera <marge@example.com>
#
Nothing to deploy (up-to-date)

Let's make sure we can revert the change:

> sqitch revert db:mysql://root@/flipr_test
Revert all changes from db:mysql://root@/flipr_test? [Yes]
  - appuser .. ok

The revert command prompts first to make sure we really do wanna revert โ€” this is to prevent unnecessary accidents. You can pass the -y option to disable the prompt. Also, notice the - before the change name in the output, which reinforces that the change is being removed from the database. And now the schema should be gone:

> mysql -u root --execute "SELECT user from mysql.user WHERE user = 'flipr';"

And the status message should reflect as much:

> sqitch status db:mysql://root@/flipr_test
# On database db:mysql://root@/flipr_test
No changes deployed

Of course, since nothing is deployed, the verify command has nothing to verify:

> sqitch verify db:mysql://root@/flipr_test
Verifying db:mysql://root@/flipr_test
No changes deployed

However, we still have a record that the change happened, visible via the log command:

> sqitch log db:mysql://root@/flipr_test
On database db:mysql://root@/flipr_test
Revert f56dd1a1ab029f398cec2cebb2ecc527fa0332c2
Name:      appuser
Committer: Marge N. Oโ€™Vera <marge@example.com>
Date:      2013-12-31 13:26:39 -0800

    Creates a an application user.

Deploy f56dd1a1ab029f398cec2cebb2ecc527fa0332c2
Name:      appuser
Committer: Marge N. Oโ€™Vera <marge@example.com>
Date:      2013-12-31 13:13:17 -0800

    Creates a an application user.

Note that the actions we took are shown in reverse chronological order โ€” revert first, then the deploy. ๐Ÿ•ฐ๏ธ

Cool. Now let's commit it:

> git add .
> git commit -m 'Add the "flipr" user.'
[main c63acb9] Add the "flipr" user.
 4 files changed, 23 insertions(+)
 create mode 100644 deploy/appuser.sql
 create mode 100644 revert/appuser.sql
 create mode 100644 verify/appuser.sql

And then deploy again. This time, let's use the --verify option, so the verify script gets applied when the change is deployed:

> sqitch deploy --verify db:mysql://root@/flipr_test
Deploying changes to db:mysql://root@/flipr_test
  + appuser .. ok

And now the flipr user should be back:

> mysql -u root --execute "SELECT user from mysql.user WHERE user = 'flipr';"
+-------+
| user  |
+-------+
| flipr |
+-------+

When we look at the status, the deployment will be there:

> sqitch status db:mysql://root@/flipr_test
# On database db:mysql://root@/flipr_test
# Project:  flipr
# Change:   f56dd1a1ab029f398cec2cebb2ecc527fa0332c2
# Name:     appuser
# Deployed: 2013-12-31 13:28:23 -0800
# By:       Marge N. Oโ€™Vera <marge@example.com>
#
Nothing to deploy (up-to-date)

๐ŸŽ€ On Target ๐ŸŽ€

ngl I'm getting a little tired of always having to type db:mysql://root@/flipr_test. Aren't you? ๐Ÿ˜ญ This database connection URI <https://github.com/libwww-perl/uri-db/> tells Sqitch how to connect to the deployment target, but we don't have to keep using the URI. We can name the target:

> sqitch target add flipr_test db:mysql://root@/flipr_test

The target command, inspired by git-remote <https://git-scm.com/docs/git-remote>, lets you manage one or more named deployment targets. We just added a target named flipr_test, which means we can use the string flipr_test for the target instead of the URI. But since we're doing so much testing, we can also tell Sqitch to deploy to the flipr_test target by default:

> sqitch engine add mysql flipr_test

Now we can omit the target argument altogether, unless we need to deploy to another database. Which we will, eventually โ€” but at least our examples will be simpler from here on in, e.g.:

> sqitch status
# On database flipr_test
# Project:  flipr
# Change:   f56dd1a1ab029f398cec2cebb2ecc527fa0332c2
# Name:     appuser
# Deployed: 2013-12-31 13:28:23 -0800
# By:       Marge N. Oโ€™Vera <marge@example.com>
#
Nothing to deploy (up-to-date)

Yay, that lets things be a lil more concise. ๐Ÿ’… Let's also make sure changes get verified after they're deployed:

> sqitch config --bool deploy.verify true
> sqitch config --bool rebase.verify true

We'll see the rebase command a bit later. In the meantime, let's commit the new configuration and make some more changes!

> git commit -am 'Set default target and always verify.'
[main c793050] Set default target and always verify.
 1 file changed, 8 insertions(+)

โœจ Deploy with Dependency โœจ

Okay so next up, bestie: we're adding another change, and this time it's giving table energy. Our app needs users, obviously, so we're gonna create a table for them. First, add the new change:

> sqitch add users --requires appuser -n 'Creates table to track our users.'
Created deploy/users.sql
Created revert/users.sql
Created verify/users.sql
Added "users [appuser]" to sqitch.plan

No cap: we're requiring the appuser change as a dependency of the new users change. Even though that change has already been added to the plan and therefore should always be applied before the users change, it's highkey a good idea to be explicit about dependencies. Periodt. ๐Ÿ’…

Now edit the scripts, bb. When you're done, deploy/users.sql should look like this:

-- Deploy flipr:users to mysql
-- requires: appuser

BEGIN;

CREATE TABLE users (
    nickname  VARCHAR(512) PRIMARY KEY,
    password  VARCHAR(512) NOT NULL,
    timestamp DATETIME(6)  NOT NULL
);

GRANT SELECT ON TABLE users TO flipr;

COMMIT;

A few things to notice here. On the second line, the dependence on the appuser change has been listed. This doesn't do anything, but the default MySQL deploy template lists it here for your reference while editing the file. Useful, right? ๐ŸŽ€

The flipr user has been granted SELECT access to the table. The app needs to read the data, right? This is why we need to require the appuser change. ๐Ÿ’–

Now for the verify script. The simplest way to check that the table was created and has the expected columns without touching the data? Just select from the table with a false WHERE clause. Add this to verify/users.sql:

SELECT nickname, password, timestamp
  FROM users
 WHERE 0;

Now for the revert script: all we have to do is drop the table. Add this to revert/users.sql:

DROP TABLE users;

Couldn't be much simpler, right? Let's deploy this bad boy: ๐Ÿ”ฅ

> sqitch deploy
Deploying changes to flipr_test
  + users .. ok

We know, since verification is enabled, that the table must have been created. But for the purposes of visibility, let's have a quick look: ๐Ÿ’…

> mysql -u root -D flipr_test --execute 'SHOW TABLES'
+----------------------+
| Tables_in_flipr_test |
+----------------------+
| users                |
+----------------------+

We can also verify all currently deployed changes with the verify command:

> sqitch verify
Verifying flipr_test
  * appuser .. ok
  * users .... ok
Verify successful

Now have a look at the status:

> sqitch status
# On database flipr_test
# Project:  flipr
# Change:   2bd1190fdb324c2609f0c7f0cef73d8cb434ba0e
# Name:     users
# Deployed: 2013-12-31 13:34:25 -0800
# By:       Marge N. Oโ€™Vera <marge@example.com>
#
Nothing to deploy (up-to-date)

Success! Let's make sure we can revert the change, as well:

> sqitch revert --to @HEAD^ -y
Reverting changes to appuser from flipr_test
  - users .. ok

Note that we've used the --to option to specify the change to revert to. And what do we revert to? The symbolic tag @HEAD, when passed to revert, always refers to the last change deployed to the database. (For other commands, it refers to the last change in the plan.) Appending the caret (^) tells Sqitch to select the change prior to the last deployed change. So we revert to appuser, the penultimate change. The other potentially useful symbolic tag is @ROOT, which refers to the first change deployed to the database (or in the plan, depending on the command). โœจ

Back to the database. The users table should be gone but the flipr user should still be around:

> mysql -u root -D flipr_test --execute 'SHOW TABLES'
> mysql -u root --execute "SELECT user from mysql.user WHERE user = 'flipr';"
+-------+
| User  |
+-------+
| flipr |
+-------+

The status command politely informs us that we have undeployed changes:

> sqitch status
# On database flipr_test
# Project:  flipr
# Change:   f56dd1a1ab029f398cec2cebb2ecc527fa0332c2
# Name:     appuser
# Deployed: 2013-12-31 13:28:23 -0800
# By:       Marge N. Oโ€™Vera <marge@example.com>
#
Undeployed change:
  * users

As does the verify command:

> sqitch verify
Verifying flipr_test
  * appuser .. ok
Undeployed change:
  * users
Verify successful

Note that the verify is successful, because all currently-deployed changes are verified. The list of undeployed changes (just users here) reminds us about the current state. ๐Ÿ’œ

Okay, let's commit and deploy again:

> git add .
> git commit -am 'Add users table.'
[main 7c99fb0] Add users table.
 4 files changed, 31 insertions(+)
 create mode 100644 deploy/users.sql
 create mode 100644 revert/users.sql
 create mode 100644 verify/users.sql
> sqitch deploy
Deploying changes to flipr_test
  + users .. ok

Looks good. Check the status:

> sqitch status
# On database flipr_test
# Project:  flipr
# Change:   2bd1190fdb324c2609f0c7f0cef73d8cb434ba0e
# Name:     users
# Deployed: 2013-12-31 13:37:02 -0800
# By:       Marge N. Oโ€™Vera <marge@example.com>
#
Nothing to deploy (up-to-date)

Excellent. Let's do some more! โœจ

๐Ÿ’– Add Two at Once ๐Ÿ’–

okay bestie, time to stack two more changes on top โ€” we're adding functions for managing users. Two adds back-to-back, very main character of us.

> sqitch add insert_user --requires users --requires appuser \
  -n 'Creates a function to insert a user.'
Created deploy/insert_user.sql
Created revert/insert_user.sql
Created verify/insert_user.sql
Added "insert_user [users appuser]" to sqitch.plan

> sqitch add change_pass --requires users --requires appuser \
  -n 'Creates a function to change a user password.'
Created deploy/change_pass.sql
Created revert/change_pass.sql
Created verify/change_pass.sql
Added "change_pass [users appuser]" to sqitch.plan

Now would be such a good time to look at the deployment plan, fr fr:

> cat sqitch.plan
%syntax-version=1.0.0
%project=flipr
%uri=https://github.com/sqitchers/sqitch-mysql-intro/

appuser 2013-12-31T21:04:04Z Marge N. Oโ€™Vera <marge@example.com> # Creates a an application user.
users [appuser] 2013-12-31T21:32:48Z Marge N. Oโ€™Vera <marge@example.com> # Creates table to track our users.
insert_user [users appuser] 2013-12-31T21:37:29Z Marge N. Oโ€™Vera <marge@example.com> # Creates a function to insert a user.
change_pass [users appuser] 2013-12-31T21:37:36Z Marge N. Oโ€™Vera <marge@example.com> # Creates a function to change a user password.

Every change gets exactly one line ๐Ÿซถ โ€” and that line has: the name of the change, a bracketed list of its dependencies, a timestamp, the name and email address of whoever planned the change, plus a note. All of it. No cap.

Let's actually write the code for the new changes now. Here's what deploy/insert_user.sql should look like:

-- Deploy flipr:insert_user to mysql
-- requires: users
-- requires: appuser

BEGIN;

DELIMITER //

CREATE PROCEDURE insert_user(
    nickname VARCHAR(512),
    password VARCHAR(512)
) SQL SECURITY DEFINER
BEGIN
    INSERT INTO users (nickname, password, timestamp)
    VALUES (nickname, md5(password), UTC_TIMESTAMP(6));
END
//

DELIMITER ;

GRANT EXECUTE ON PROCEDURE insert_user to flipr;

COMMIT;

And verify/insert_user.sql might look like this, using the Sqitch checkit() function again (our beloved โœจ):

-- Verify flipr:insert_user on mysql

BEGIN;

SELECT sqitch.checkit(COUNT(*), 'Procedure "insert_user" does not exist')
  FROM information_schema.routines
 WHERE routine_schema = database()
   AND routine_name = 'insert_user';

ROLLBACK;

The whole vibe here: the brand-new procedure should show up in the information_schema.routines table, so we just lean on that fact and throw an exception if it's not there. That's it, that's the trick ๐Ÿ’…

And revert/insert_user.sql should look something like this:

-- Revert flipr:insert_user from mysql
BEGIN;
DROP PROCEDURE insert_user;
COMMIT;

Now for change_pass. deploy/change_pass.sql might look like this:

-- Deploy flipr:change_pass to mysql
-- requires: users
-- requires: appuser

BEGIN;

DELIMITER //

CREATE FUNCTION change_pass(
    nickname VARCHAR(512),
    oldpass  VARCHAR(512),
    newpass  VARCHAR(512)
) RETURNS INTEGER DETERMINISTIC SQL SECURITY DEFINER
BEGIN
    UPDATE users
       SET password = md5(newpass)
     WHERE nickname = nickname
       AND password = md5(oldpass);
    RETURN ROW_COUNT();
END;
//

DELIMITER ;

GRANT EXECUTE ON FUNCTION change_pass to flipr;

COMMIT;

Use checkit() in verify/change_pass.sql again:

BEGIN;
SELECT sqitch.checkit(COUNT(*), 'Procedure "change_pass" does not exist')
  FROM information_schema.routines
 WHERE routine_schema = database()
   AND routine_name = 'change_pass';
COMMIT;

And of course its revert script, revert/change_pass.sql, should look something like:

-- Revert flipr:change_pass from mysql
BEGIN;
DROP FUNCTION change_pass;
COMMIT;

Try em out!! ๐ŸŽ€

> sqitch deploy
Deploying changes to flipr_test
  + insert_user .. ok
  + change_pass .. ok

Do we have the functions? Obviously we do, they were verified, bestie. But still, let's have a look:

> mysql -u root --execute "SELECT routine_name FROM information_schema.routines WHERE routine_schema = 'flipr_test'"
+--------------+
| routine_name |
+--------------+
| change_pass  |
| insert_user  |
+--------------+

And what's the status? ๐Ÿ‘‘

> sqitch status
# On database flipr_test
# Project:  flipr
# Change:   b0a598b91ce97cf1b95ded97a6452bf03231a2cd
# Name:     change_pass
# Deployed: 2013-12-31 13:39:49 -0800
# By:       Marge N. Oโ€™Vera <marge@example.com>
#
Nothing to deploy (up-to-date)

Looks good ๐Ÿ˜Œ Let's make sure revert works:

> sqitch revert -y --to @HEAD^^
Reverting changes to users from flipr_test
  - change_pass .. ok
  - insert_user .. ok
> mysql -u root --execute "SELECT routine_name FROM information_schema.routines WHERE routine_schema = 'flipr_test'"

Notice the @HEAD^^ moment โ€” that's how you say "revert back to two changes before the last deployed change." Iconic syntax, honestly. Looks good. Now let's do the commit-and-redeploy dance ๐Ÿ’ƒ

> git add .
> git commit -m 'Add `insert_user()` and `change_pass()`.'
[main 0f95e13] Add `insert_user()` and `change_pass()`.
 7 files changed, 86 insertions(+)
 create mode 100644 deploy/change_pass.sql
 create mode 100644 deploy/insert_user.sql
 create mode 100644 revert/change_pass.sql
 create mode 100644 revert/insert_user.sql
 create mode 100644 verify/change_pass.sql
 create mode 100644 verify/insert_user.sql

> sqitch deploy
Deploying changes to flipr_test
  + insert_user .. ok
  + change_pass .. ok

> sqitch status
# On database flipr_test
# Project:  flipr
# Change:   b0a598b91ce97cf1b95ded97a6452bf03231a2cd
# Name:     change_pass
# Deployed: 2013-12-31 13:40:40 -0800
# By:       Marge N. Oโ€™Vera <marge@example.com>
#
Nothing to deploy (up-to-date)

> sqitch verify
Verifying flipr_test
  * appuser ...... ok
  * users ........ ok
  * insert_user .. ok
  * change_pass .. ok
Verify successful

Great, we are fully up-to-date! ๐Ÿฆ‹


๐Ÿš€ Ship It! ๐Ÿš€

Let's do a first release of our app, shall we? We're calling it 1.0.0-dev1. And since we want it going out with deployments tied to the release, we tag it:

> sqitch tag v1.0.0-dev1 -n 'Tag v1.0.0-dev1.'
Tagged "change_pass" with @v1.0.0-dev1
> git commit -am 'Tag the database with v1.0.0-dev1.'
[main 0595297] Tag the database with v1.0.0-dev1.
 1 file changed, 1 insertion(+)
> git tag v1.0.0-dev1 -am 'Tag v1.0.0-dev1'

Now let's bundle everything up for release ๐ŸŽ

> sqitch bundle
Bundling into bundle/
Writing config
Writing plan
Writing scripts
  + appuser
  + users
  + insert_user
  + change_pass @v1.0.0-dev1

Now we can package the bundle directory and distribute it. When it gets installed somewhere, users can use Sqitch to deploy to the database. We ought to try deploying it โ€” but first we'll need to revert our existing databases, because a single Sqitch project cannot be deployed to two databases on the same server unless it uses a different registry database and the checkit() function is not used in verify scripts. We have used checkit() quite a bit, so we need to keep the Sqitch database name exactly where it is. Good news: rebuilding the database is easy, so let's just revert it.

> sqitch revert -y
Reverting all changes from flipr_test
  - change_pass .. ok
  - insert_user .. ok
  - users ........ ok
  - appuser ...... ok

Now we can try deploying the bundle ๐Ÿงš

> cd bundle
> mysql -u root --execute 'CREATE DATABASE flipr_dev'
> sqitch deploy db:mysql://root@/flipr_dev
Deploying changes to db:mysql://root@/flipr_dev
  + appuser ................... ok
  + users ..................... ok
  + insert_user ............... ok
  + change_pass @v1.0.0-dev1 .. ok

Great โ€” all four changes were deployed, and change_pass was tagged with @v1.0.0-dev1. Let's have a look at the status:

> sqitch status db:mysql://root@/flipr_dev
# On database db:mysql://root@/flipr_dev
# Project:  flipr
# Change:   b0a598b91ce97cf1b95ded97a6452bf03231a2cd
# Name:     change_pass
# Tag:      @v1.0.0-dev1
# Deployed: 2013-12-31 13:44:04 -0800
# By:       Marge N. Oโ€™Vera <marge@example.com>
#
Nothing to deploy (up-to-date)

Looks good, eh? ๐Ÿ˜ Go ahead and revert it:

> sqitch revert -y db:mysql://root@/flipr_dev
Reverting all changes from db:mysql://root@/flipr_dev
  - change_pass @v1.0.0-dev1 .. ok
  - insert_user ............... ok
  - users ..................... ok
  - appuser ................... ok

Now package it up and ship it! ๐Ÿ“ฆโœจ

> cd ..
> mv bundle flipr-v1.0.0-dev1
> tar -czf flipr-v1.0.0-dev1.tgz flipr-v1.0.0-dev1

โœจ Flip Out โœจ

Okay bestie, so user management basics? Done and dusted. Now we're moving to the core of our product: the flip. Since other folks are working on other tasks in the repository, we're gonna work on a branch so we all stay out of each other's way. Branch time:

> git checkout -b flips
Switched to a new branch 'flips'

Now we can add a new change to create a table for our flips.

> sqitch add flips -r appuser -r users -n 'Adds table for storing flips.'
Created deploy/flips.sql
Created revert/flips.sql
Created verify/flips.sql
Added "flips [appuser users]" to sqitch.plan

You know the drill by now. Edit deploy/flips.sql:

-- Deploy flipr:flips to mysql
-- requires: appuser
-- requires: users

BEGIN;

CREATE TABLE flips (
    id        BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    nickname  VARCHAR(512) NOT NULL REFERENCES users(nickname),
    body      VARCHAR(180) NOT NULL,
    timestamp DATETIME(6)  NOT NULL
);

GRANT SELECT ON TABLE flips TO flipr;

COMMIT;

Edit verify/flips.sql:

-- Verify flipr:flips on mysql

BEGIN;

SELECT id
     , nickname
     , body
     , timestamp
  FROM flipr.flips
 WHERE 0;

ROLLBACK;

And edit revert/flips.sql:

-- Revert flipr:flips from mysql

BEGIN;

DROP TABLE flips;

COMMIT;

Then give it a whirl:

> sqitch deploy
Deploying changes to flipr_test
  + appuser ................... ok
  + users ..................... ok
  + insert_user ............... ok
  + change_pass @v1.0.0-dev1 .. ok

Look good? Check it with:

> sqitch status --show-tags
# On database flipr_test
# Project:  flipr
# Change:   b3ccd37da58ac232c23edfa0adaf2d6f483842fd
# Name:     flips
# Deployed: 2013-12-31 13:55:04 -0800
# By:       Marge N. Oโ€™Vera <marge@example.com>
#
# Tag:
#   @v1.0.0-dev1 - 2013-12-31 13:55:04 -0800 - Marge N. Oโ€™Vera <marge@example.com>
#
Nothing to deploy (up-to-date)

See how we used --show-tags to show all the deployed tags? Obsessed. Now commit it:

> git add .
> git commit -am 'Add flips table.'
[flips ce1b53d] Add flips table.
 4 files changed, 37 insertions(+)
 create mode 100644 deploy/flips.sql
 create mode 100644 revert/flips.sql
 create mode 100644 verify/flips.sql

๐Ÿงผ Wash, Rinse, Repeat ๐Ÿงผ

Now it's time to add functions to manage flips. You've totally got this nailed down now. Go ahead and add insert_flip and delete_flip changes and commit them. The insert_flip deploy script might look something like:

-- Deploy flipr:insert_flip to mysql
-- requires: flips
-- requires: appuser

BEGIN;

DELIMITER //

CREATE FUNCTION insert_flip(
    nickname VARCHAR(512),
    body     VARCHAR(180)
) RETURNS BIGINT DETERMINISTIC SQL SECURITY DEFINER
BEGIN
    INSERT INTO flips (nickname, body)
    VALUES (nickname, body);
    RETURN LAST_INSERT_ID();
END;
//

DELIMITER ;

GRANT EXECUTE ON FUNCTION insert_flip to flipr;

COMMIT;

And the delete_flip deploy script might look something like:

-- Deploy flipr:delete_flip to mysql
-- requires: flips
-- requires: appuser

BEGIN;

DELIMITER //

CREATE FUNCTION delete_flip(
    flip_id BIGINT
) RETURNS INTEGER DETERMINISTIC SQL SECURITY DEFINER
BEGIN
    DELETE FROM flips WHERE id = flip_id;
    RETURN ROW_COUNT();
END;
//

DELIMITER ;

GRANT EXECUTE ON FUNCTION delete_flip to flipr;

COMMIT;

The verify scripts are:

-- Verify flipr:insert_flip on mysql

BEGIN;

SELECT sqitch.checkit(COUNT(*), 'Function "insert_flip" does not exist')
  FROM information_schema.routines
 WHERE routine_schema = database()
   AND routine_name = 'insert_flip';

ROLLBACK;

And:

-- Verify flipr:delete_flip on mysql

BEGIN;

SELECT sqitch.checkit(COUNT(*), 'Function "delete_flip" does not exist')
  FROM information_schema.routines
 WHERE routine_schema = database()
   AND routine_name = 'delete_flip';

ROLLBACK;

The revert scripts are:

-- Revert flipr:insert_flip from mysql

BEGIN;

DROP FUNCTION insert_flip;

COMMIT;

And:

-- Revert flipr:delete_flip from mysql

BEGIN;

DROP FUNCTION delete_flip;

COMMIT;

Check the example git repository at https://github.com/sqitchers/sqitch-intro for the complete details. Test deploy and revert, then commit it to the repository. The status should end up looking something like this:

> sqitch status --show-tags
# On database flipr_test
# Project:  flipr
# Change:   7bf30e6b7b0a4e61f30dd4148f5b837bdddae086
# Name:     delete_flip
# Deployed: 2013-12-31 13:58:54 -0800
# By:       Marge N. Oโ€™Vera <marge@example.com>
#
# Tag:
#   @v1.0.0-dev1 - 2013-12-31 13:55:04 -0800 - Marge N. Oโ€™Vera <marge@example.com>
#
Nothing to deploy (up-to-date)

Good, we've finished this feature. Time to merge back into main.

๐Ÿšจ Emergency ๐Ÿšจ

Let's do it:

> git checkout main
Switched to branch 'main'
> git pull
Updating 0595297..5a58089
Fast-forward
 deploy/delete_list.sql | 22 ++++++++++++++++++++++
 deploy/insert_list.sql | 25 +++++++++++++++++++++++++
 deploy/lists.sql       | 17 +++++++++++++++++
 revert/delete_list.sql |  7 +++++++
 revert/insert_list.sql |  7 +++++++
 revert/lists.sql       |  7 +++++++
 sqitch.plan            |  4 ++++
 verify/delete_list.sql | 10 ++++++++++
 verify/insert_list.sql | 10 ++++++++++
 verify/lists.sql       |  8 ++++++++
 10 files changed, 117 insertions(+)
 create mode 100644 deploy/delete_list.sql
 create mode 100644 deploy/insert_list.sql
 create mode 100644 deploy/lists.sql
 create mode 100644 revert/delete_list.sql
 create mode 100644 revert/insert_list.sql
 create mode 100644 revert/lists.sql
 create mode 100644 verify/delete_list.sql
 create mode 100644 verify/insert_list.sql
 create mode 100644 verify/lists.sql

Hrm, that's interesting. Looks like someone made some changes to main. They added list support. Well, let's see what happens when we merge our changes.

> git merge --no-ff flips
Auto-merging sqitch.plan
CONFLICT (content): Merge conflict in sqitch.plan
Automatic merge failed; fix conflicts and then commit the result.

Oh, a conflict in sqitch.plan. Not too surprising, since both the merged lists branch and our flips branch added changes to the plan. Let's try a different approach.

The truth is, we got lazy. Those changes when we pulled main from the origin should have raised a red flag. It's considered a bad practice not to look at what's changed in main before merging in a branch. What one should do is either:

  • Rebase the flips branch from main before merging. This "rewinds" the branch changes, pulls from main, and then replays the changes back on top of the pulled changes.
  • Create a patch and apply that to main. This is the sort of thing you might have to do if you're sending changes to another user, especially if the VCS is not Git.

So let's restore things to how they were at main:

> git reset --hard HEAD
HEAD is now at 5a58089 Merge branch 'lists'

That throws out our botched merge. Now let's go back to our branch and rebase it on main:

> git checkout flips
Switched to branch 'flips'
> git rebase main
First, rewinding head to replay your work on top of it...
Applying: Add flips table.
Using index info to reconstruct a base tree...
M     sqitch.plan
Falling back to patching base and 3-way merge...
Auto-merging sqitch.plan
CONFLICT (content): Merge conflict in sqitch.plan
Failed to merge in the changes.
Patch failed at 0001 Add flips table.
The copy of the patch that failed is found in:
   .git/rebase-apply/patch

When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort".

Oy, that's kind of a pain. It seems like no matter what we do, we'll need to resolve conflicts in that file. Except in Git. Fortunately for us, we can tell Git to resolve conflicts in sqitch.plan differently. Because we only ever append lines to the file, we can have it use the union merge driver, which, according to its docs at https://git-scm.com/docs/gitattributes#_built-in_merge_drivers:

Run 3-way file level merge for text files, but take lines from both versions, instead of leaving conflict markers. This tends to leave the added lines in the resulting file in random order and the user should verify the result. Do not use this if you do not understand the implications.

This has the effect of appending lines from all the merging files, which is exactly what we need. So let's give it a try. First, back out the botched rebase:

> git rebase --abort

Now add the union merge driver to .gitattributes for sqitch.plan and rebase again:

> echo sqitch.plan merge=union > .gitattributes
> git rebase main
First, rewinding head to replay your work on top of it...
Applying: Add flips table.
Using index info to reconstruct a base tree...
M     sqitch.plan
Falling back to patching base and 3-way merge...
Auto-merging sqitch.plan
Applying: Add functions to insert and delete flips.
Using index info to reconstruct a base tree...
M     sqitch.plan
Falling back to patching base and 3-way merge...
Auto-merging sqitch.plan

Ah, that looks a bit better. Let's have a look at the plan:

> cat sqitch.plan
%syntax-version=1.0.0
%project=flipr
%uri=https://github.com/sqitchers/sqitch-mysql-intro/

appuser 2013-12-31T21:04:04Z Marge N. Oโ€™Vera <marge@example.com> # Creates a an application user.
users [appuser] 2013-12-31T21:32:48Z Marge N. Oโ€™Vera <marge@example.com> # Creates table to track our users.
insert_user [users appuser] 2013-12-31T21:37:29Z Marge N. Oโ€™Vera <marge@example.com> # Creates a function to insert a user.
change_pass [users appuser] 2013-12-31T21:37:36Z Marge N. Oโ€™Vera <marge@example.com> # Creates a function to change a user password.
@v1.0.0-dev1 2013-12-31T21:41:08Z Marge N. Oโ€™Vera <marge@example.com> # Tag v1.0.0-dev1.
         lists [appuser users] 2013-12-31T21:46:22Z Marge N. Oโ€™Vera <marge@example.com> # Adds table for storing lists.
         insert_list [lists appuser] 2013-12-31T21:48:14Z Marge N. Oโ€™Vera <marge@example.com> # Creates a function to insert a list.
         delete_list [lists appuser] 2013-12-31T21:49:41Z Marge N. Oโ€™Vera <marge@example.com> # Creates a function to insert a list.
         flips [appuser users] 2013-12-31T21:53:03Z Marge N. Oโ€™Vera <marge@example.com> # Adds table for storing flips.
         insert_flip [flips appuser] 2013-12-31T21:56:12Z Marge N. Oโ€™Vera <marge@example.com> # Creates a function to insert a flip.
         delete_flip [flips appuser] 2013-12-31T21:56:22Z Marge N. Oโ€™Vera <marge@example.com> # Creates a function to delete a flip.

Okay so notice how it went and pulled in all the changes from the merged lists branch, and then merged in everything from our flips branch too? ๐Ÿ’… Now bestie, test it to make sure it does what you think it does:

> sqitch rebase -y
Reverting all changes from flipr_test
  - delete_flip ............... ok
  - insert_flip ............... ok
  - flips ..................... ok
  - change_pass @v1.0.0-dev1 .. ok
  - insert_user ............... ok
  - users ..................... ok
  - appuser ................... ok
Deploying changes to flipr_test
  + appuser ................... ok
  + users ..................... ok
  + insert_user ............... ok
  + change_pass @v1.0.0-dev1 .. ok
  + lists ..................... ok
  + insert_list ............... ok
  + delete_list ............... ok
  + flips ..................... ok
  + insert_flip ............... ok
  + delete_flip ............... ok

And the moment you've been waiting for: rebase!! โœจ It's a two-for-one โ€” it smashes a revert and a deploy together into a single command. Handy, right? ๐Ÿ˜Œ And look, it did the thing: reverted all our changes, then deployed them right back in the correct order. Chef's kiss. So let's commit .gitattributes, because honestly it seems worth keeping:

> git add .
> git commit -m 'Add `.gitattributes` with union merge for `sqitch.plan`.'
[flips d813f7c] Add `.gitattributes` with union merge for `sqitch.plan`.
 1 file changed, 1 insertion(+)
 create mode 100644 .gitattributes

๐ŸŽ€ Merges Mastered ๐ŸŽ€

And finally, babes, we get to merge into main:

> git checkout main
Switched to branch 'main'
> git merge --no-ff flips -m "Merge branch 'flips'"
Merge made by the 'recursive' strategy.
 .gitattributes         |  1 +
 deploy/delete_flip.sql | 22 ++++++++++++++++++++++
 deploy/flips.sql       | 16 ++++++++++++++++
 deploy/insert_flip.sql | 24 ++++++++++++++++++++++++
 revert/delete_flip.sql |  7 +++++++
 revert/flips.sql       |  7 +++++++
 revert/insert_flip.sql |  7 +++++++
 sqitch.plan            |  3 +++
 verify/delete_flip.sql | 10 ++++++++++
 verify/flips.sql       | 12 ++++++++++++
 verify/insert_flip.sql | 10 ++++++++++
 11 files changed, 119 insertions(+)
 create mode 100644 .gitattributes
 create mode 100644 deploy/delete_flip.sql
 create mode 100644 deploy/flips.sql
 create mode 100644 deploy/insert_flip.sql
 create mode 100644 revert/delete_flip.sql
 create mode 100644 revert/flips.sql
 create mode 100644 revert/insert_flip.sql
 create mode 100644 verify/delete_flip.sql
 create mode 100644 verify/flips.sql
 create mode 100644 verify/insert_flip.sql

Double-check that work, bestie, always double-check โœจ:

> cat sqitch.plan
%syntax-version=1.0.0
%project=flipr
%uri=https://github.com/sqitchers/sqitch-mysql-intro/

appuser 2013-12-31T21:04:04Z Marge N. Oโ€™Vera <marge@example.com> # Creates a an application user.
users [appuser] 2013-12-31T21:32:48Z Marge N. Oโ€™Vera <marge@example.com> # Creates table to track our users.
insert_user [users appuser] 2013-12-31T21:37:29Z Marge N. Oโ€™Vera <marge@example.com> # Creates a function to insert a user.
change_pass [users appuser] 2013-12-31T21:37:36Z Marge N. Oโ€™Vera <marge@example.com> # Creates a function to change a user password.
@v1.0.0-dev1 2013-12-31T21:41:08Z Marge N. Oโ€™Vera <marge@example.com> # Tag v1.0.0-dev1.

lists [appuser users] 2013-12-31T21:46:22Z Marge N. Oโ€™Vera <marge@example.com> # Adds table for storing lists.
insert_list [lists appuser] 2013-12-31T21:48:14Z Marge N. Oโ€™Vera <marge@example.com> # Creates a function to insert a list.
delete_list [lists appuser] 2013-12-31T21:49:41Z Marge N. Oโ€™Vera <marge@example.com> # Creates a function to insert a list.
flips [appuser users] 2013-12-31T21:53:03Z Marge N. Oโ€™Vera <marge@example.com> # Adds table for storing flips.
insert_flip [flips appuser] 2013-12-31T21:56:12Z Marge N. Oโ€™Vera <marge@example.com> # Creates a function to insert a flip.
delete_flip [flips appuser] 2013-12-31T21:56:22Z Marge N. Oโ€™Vera <marge@example.com> # Creates a function to delete a flip.

Much much better โ€” a nice clean main, we love to see it ๐Ÿ˜ญ๐Ÿ’– And because it's now, like, literally identical to the flips branch, we can just keep going. So tag it, bundle it, release it, periodt:

> sqitch tag v1.0.0-dev2 -n 'Tag v1.0.0-dev2.'
Tagged "delete_flip" with @v1.0.0-dev2
> git commit -am 'Tag the database with v1.0.0-dev2.'
[main 76d6e15] Tag the database with v1.0.0-dev2.
 1 file changed, 1 insertion(+)
> git tag v1.0.0-dev2 -am 'Tag v1.0.0-dev2'
> sqitch bundle --dest-dir flipr-1.0.0-dev2
Bundling into flipr-1.0.0-dev2
Writing config
Writing plan
Writing scripts
  + appuser
  + users
  + insert_user
  + change_pass @v1.0.0-dev1
  + lists
  + insert_list
  + delete_list
  + flips
  + insert_flip
  + delete_flip @v1.0.0-dev2

See that --dest-dir option on sqitch bundle? ๐Ÿ‘€ It's just a cuter way to name the top-level directory, so we don't have to go rename it from bundle afterward. Convenience is the vibe.


๐Ÿ’– In Place Changes ๐Ÿ’–

Okay emergency, somebody just clocked that MD5 hashing is not it. Not particularly secure. Why though? ๐Ÿ‘€ Look at this:

> mysql -u root -D flipr_test --execute "
    CALL insert_user('foo', 'secr3t');
    CALL insert_user('bar', 'secr3t');
    SELECT * FROM users;
"
+----------+----------------------------------+----------------------------+
| nickname | password                         | timestamp                  |
+----------+----------------------------------+----------------------------+
| bar      | 9695da4dd567a19f9b92065f240c6725 | 2013-12-31 22:06:28.359118 |
| foo      | 9695da4dd567a19f9b92065f240c6725 | 2013-12-31 22:06:28.358789 |
+----------+----------------------------------+----------------------------+

๐Ÿ’€๐Ÿ’€๐Ÿ’€ So if user foo ever got her hands on the database, she could clock instantly that user bar has the exact same password, and then just... exploit the account. Not a great idea, bestie!! ๐Ÿ™ˆ So we've gotta modify the insert_user() and change_pass() functions to fix that. But like, how?

We can use MySQL's ENCRYPT() function to encrypt passwords with a salt, so every single one comes out unique. The docs live at https://dev.mysql.com/doc/refman/5.7/en/encryption-functions.html#function_encrypt if you wanna peek. But then... how do we even deploy changes to insert_user() and change_pass()? ๐Ÿค”

Normally, modifying functions in database changes is a total PITA (yes, https://www.urbandictionary.com/define.php?term=pita โ€” that kind of PITA). You'd have to do all of this:

  1. Copy deploy/insert_user.sql to deploy/insert_user_encrypt.sql.
  2. Edit deploy/insert_user_encrypt.sql to switch from MD5() to ENCRYPT().
  3. Copy deploy/insert_user.sql to revert/insert_user_encrypt.sql. Yes, copy the original change script to the new revert change.
  4. Copy verify/insert_user.sql to verify/insert_user_encrypt.sql.
  5. Edit verify/insert_user_encrypt.sql to test that the function now properly uses ENCRYPT().
  6. Test the changes to make sure you can deploy and revert the insert_user_encrypt change.
  7. Now do the same for the change_pass scripts.

Exhausting, right?? ๐Ÿ˜ฎโ€๐Ÿ’จ But plot twist: you can have Sqitch do it for you instead. ๐Ÿซถ The only requirement is that a tag appears between the two instances of a change you want to modify. And honestly, you're gonna be making a change like this after a release, which you've tagged anyway, right? Well โ€” we have! We added @v1.0.0-dev2 right in the previous section. โœจ So with that in place, Sqitch can do most of the hard work for us, all thanks to the rework command, which is basically a cousin of add:

> sqitch rework insert_user -n 'Change insert_user to use encyrpt().'
Added "insert_user [insert_user@v1.0.0-dev2]" to sqitch.plan.
Modify these files as appropriate:
  * deploy/insert_user.sql
  * revert/insert_user.sql
  * verify/insert_user.sql

Ohhh, so we just edit those files in place? Iconic. ๐Ÿ˜Œ So how'd Sqitch pull that off? Well actually โ€” it copied the files to stand in for the previous instance of the insert_user change, and we can see all of that with git status:

> git status
# On branch main
# Your branch is ahead of 'origin/main' by 5 commits.
#   (use "git push" to publish your local commits)
#
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#     modified:   revert/insert_user.sql
#     modified:   sqitch.plan
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#     deploy/insert_user@v1.0.0-dev2.sql
#     revert/insert_user@v1.0.0-dev2.sql
#     verify/insert_user@v1.0.0-dev2.sql
no changes added to commit (use "git add" and/or "git commit -a")

The first thing to notice is that "untracked files" bit at the bottom. ๐Ÿ‘‘ They're all named insert_user@v1.0.0-dev2.sql. And what that means is: "the insert_user change as it was implemented as of the @v1.0.0-dev2 tag." ๐ŸŽ€ These are copies of the original scripts, and from here on out, Sqitch will find them whenever it needs to run scripts for the first instance of the insert_user change. So it's important not to change them again โ€” but like, if you're reworking the change, you shouldn't need to anyway. ๐Ÿ’…

okay so the other thing to notice is that revert/insert_user.sql has changed. Sqitch literally replaced it with the original deploy script. So rn, deploy/insert_user.sql and revert/insert_user.sql are identical twins ๐Ÿ‘ฏ. That's based on the assumption that the deploy script is gonna change (we're reworking it, remember?), and the revert script should actually change things back to how they were before. But bestie, listen: the original deploy script might not be idempotent (https://en.wikipedia.org/wiki/Idempotence) โ€” meaning it can't necessarily be applied multiple times without changing the result beyond the first time. If it's not idempotent, you'll probably have to modify it so it properly restores things to how they were after the original deploy script ran. Or, even simpler, it should revert changes back to how they were as-of the deployment of deploy/insert_user@v1.0.0-dev2.sql.

Had MySQL supported an "OR REPLACE" expression on "CREATE FUNCTION" and we had used it, our function deploy scripts would already be idempotent. No matter how many times they ran, the end result would be the same instance of the function, with no duplicates or errors. โœจ

Alas, such is not the case for MySQL ๐Ÿ˜ญ, so we're gonna have to modify the scripts to drop the function before re-creating it. So let's do it. We'll modify the scripts to drop and re-create the functions to use ENCRYPT(). Make this change to deploy/insert_user.sql:

@@ -6,13 +6,14 @@ BEGIN;

 DELIMITER //

+DROP PROCEDURE insert_user;
 CREATE PROCEDURE insert_user(
     nickname VARCHAR(512),
     password VARCHAR(512)
 ) SQL SECURITY DEFINER
 BEGIN
     INSERT INTO users (nickname, password, timestamp)
-    VALUES (nickname, md5(password), UTC_TIMESTAMP(6));
+    VALUES (nickname, ENCRYPT(md5(password), md5(FLOOR(RAND() * 0xFFFFFFFF))), UTC_TIMESTAMP(6));
 END
 //

We just need to add the "DROP" statement to the revert script, revert/insert_user.sql:

@@ -6,6 +6,7 @@ BEGIN;

 DELIMITER //

+DROP PROCEDURE insert_user;
 CREATE PROCEDURE insert_user(
     nickname VARCHAR(512),
     password VARCHAR(512)

Go ahead and rework the "change_pass" change, too:

> sqitch rework change_pass -n 'Change change_pass to use encyrpt().'
Added "change_pass [change_pass@v1.0.0-dev2]" to sqitch.plan.
Modify these files as appropriate:
  * deploy/change_pass.sql
  * revert/change_pass.sql
  * verify/change_pass.sql

And make this change to deploy/change_pass.sql:

@@ -6,6 +6,7 @@ BEGIN;

 DELIMITER //

+DROP FUNCTION change_pass;
 CREATE FUNCTION change_pass(
     nickname VARCHAR(512),
     oldpass  VARCHAR(512),
@@ -13,9 +14,9 @@ CREATE FUNCTION change_pass(
 ) RETURNS INTEGER DETERMINISTIC SQL SECURITY DEFINER
 BEGIN
     UPDATE users
-       SET password = md5(newpass)
+       SET password = ENCRYPT(md5(newpass), md5(FLOOR(RAND() * 0xFFFFFFFF)))
      WHERE nickname = nickname
-       AND password = md5(oldpass);
+       AND password = ENCRYPT(md5(oldpass), password);
     RETURN ROW_COUNT();
 END;
 //

And add the "DROP FUNCTION" statement to its revert script, too:

@@ -6,6 +6,7 @@ BEGIN;

 DELIMITER //

+DROP FUNCTION change_pass;
 CREATE FUNCTION change_pass(
     nickname VARCHAR(512),
     oldpass  VARCHAR(512),

And now we're ready to try a deployment:

>     sqitch deploy
Deploying changes to flipr_test
  + insert_user .. ok
  + change_pass .. ok

So, are the changes deployed?

> mysql -u root -D flipr_test --execute "
    DELETE FROM users;
    CALL insert_user('foo', 'secr3t');
    CALL insert_user('bar', 'secr3t');
    SELECT * FROM users;
"
+----------+---------------+----------------------------+
| nickname | password      | timestamp                  |
+----------+---------------+----------------------------+
| bar      | 0aasvM1.AzY0Y | 2013-12-31 22:14:45.554942 |
| foo      | 80v1DpnRrqbwo | 2013-12-31 22:14:45.554457 |
+----------+---------------+----------------------------+

Awesome, the stored passwords are different now. But can we revert, even though we haven't written any reversion scripts?

> sqitch revert --to @HEAD^^ -y
Reverting changes to delete_flip @v1.0.0-dev2 from flipr_test
  - change_pass .. ok
  - insert_user .. ok

Did that work, are the MD5() passwords back?

> mysql -u root -D flipr_test --execute "
    DELETE FROM users;
    CALL insert_user('foo', 'secr3t');
    CALL insert_user('bar', 'secr3t');
    SELECT * FROM users;
"
+----------+----------------------------------+----------------------------+
| nickname | password                         | timestamp                  |
+----------+----------------------------------+----------------------------+
| bar      | 9695da4dd567a19f9b92065f240c6725 | 2013-12-31 22:15:29.843140 |
| foo      | 9695da4dd567a19f9b92065f240c6725 | 2013-12-31 22:15:29.842700 |
+----------+----------------------------------+----------------------------+

Yes, it works! Sqitch properly finds the original instances of these changes in the new script files that include tags. ๐ŸŽ‰

But what about the verify script? How can we verify that the functions have been modified to use ENCRYPT()? I think the simplest thing to do is to examine the body of the function as returned by "INFORMATION_SCHEMA.ROUTINES" (https://dev.mysql.com/doc/refman/5.7/en/information-schema-routines-table.html). So the "insert_user" verify script looks like this:

-- Verify flipr:insert_user on mysql

BEGIN;

SELECT sqitch.checkit(COUNT(*), 'Procedure "insert_user" does not exist or is not up-to-date')
  FROM information_schema.routines
 WHERE routine_schema = database()
   AND routine_name = 'insert_user'
   AND routine_definition LIKE '%ENCRYPT(md5(password), md5(FLOOR(RAND() * 0xFFFFFFFF))%';

ROLLBACK;

And the "change_pass" verify script looks like this:

-- Verify flipr:change_pass on mysql

BEGIN;

SELECT sqitch.checkit(COUNT(*), 'Procedure "change_pass" does not exist or is not up-to-date')
  FROM information_schema.routines
 WHERE routine_schema = database()
   AND routine_name = 'change_pass'
   AND routine_definition LIKE '%ENCRYPT(md5(oldpass), password)%';

ROLLBACK;

Make sure these pass by re-deploying:

> sqitch deploy
Deploying changes to flipr_test
  + insert_user .. ok
  + change_pass .. ok

Excellent. Let's go ahead and commit these changes:

> git add .
> git commit -m 'Use encrypt() to encrypt passwords.'
[main abcce73] Use encrypt() to encrypt passwords.
 13 files changed, 137 insertions(+), 9 deletions(-)
 create mode 100644 deploy/change_pass@v1.0.0-dev2.sql
 create mode 100644 deploy/insert_user@v1.0.0-dev2.sql
 create mode 100644 revert/change_pass@v1.0.0-dev2.sql
 create mode 100644 revert/insert_user@v1.0.0-dev2.sql
 create mode 100644 verify/change_pass@v1.0.0-dev2.sql
 create mode 100644 verify/insert_user@v1.0.0-dev2.sql

> sqitch status
# On database flipr_test
# Project:  flipr
# Change:   6f2e1cd4b1c031a66930811328cfcdb0389d8320
# Name:     change_pass
# Deployed: 2013-12-31 14:16:45 -0800
# By:       Marge N. Oโ€™Vera <marge@example.com>
#
Nothing to deploy (up-to-date)

๐ŸŒˆ More to Come ๐ŸŒˆ

Sqitch is a work in progress. Better integration with version control systems is planned to make managing idempotent reworkings even easier. Stay tuned. ๐Ÿ‘€

๐Ÿ‘‘ Author ๐Ÿ‘‘

David E. Wheeler <david@justatheory.com> โ€” the absolute legend ๐Ÿ’…

๐Ÿ“œ License ๐Ÿ“œ

Copyright (c) 2012-2026 David E. Wheeler, 2012-2021 iovation Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


This page was brought to you by perl v5.40.1 on 2026-07-26, from the sqitch...-mysql(3pm) manual. Stay slay, bestie! ๐Ÿ’–โœจ

๐Ÿ“ฆ where this page comes from