David E. Wheeler > App-Sqitch-0.973 > sqitchtutorial-sqlite

Download:
App-Sqitch-0.973.tar.gz

Annotate this POD

Website

View/Report Bugs
Source   Latest Release: App-Sqitch-0.992

Name ^

sqitchtutorial-sqlite - A tutorial introduction to Sqitch change management on SQLite

Synopsis ^

  sqitch *

Description ^

This tutorial explains how to create a sqitch-enabled SQLite project, use a VCS for deployment planning, and work with other developers to make sure changes remain in sync and in the proper order.

We'll start by creating new project from scratch, a fictional antisocial networking site called Flipr. All examples use Git as the VCS and SQLite as the storage engine.

Starting a New Project ^

Usually the first thing to do when starting a new project is to create a source code repository. So let's do that 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.'
  [master (root-commit) be9b283] Initialize project, add README.
   1 file changed, 37 insertions(+)
   create mode 100644 README.md

If you're a Git user and want to follow along the history, the repository used in these examples is on GitHub.

Now that we have a repository, let's get started with Sqitch. Every Sqitch project must have a name associated with it, and, optionally, a unique URI. We recommend including the URI, as it increases the uniqueness of object identifiers internally, so let's specify one when we initialize Sqitch:

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

Let's have a look at sqitch.conf:

  > cat sqitch.conf
  [core]
        engine = sqlite
        # plan_file = sqitch.plan
        # top_dir = .
        # deploy_dir = deploy
        # revert_dir = revert
        # verify_dir = verify
        # extension = sql
  # [core "sqlite"]
        # db_name =
        # client = sqlite3
        # sqitch_db =

Good, it picked up on the fact that we're creating changes for the SQLite engine, thanks to the --engine sqlite option, and saved it to the file. Furthermore, it wrote a commented-out [core "sqlite"] section with all the available SQLite engine-specific settings commented out and ready to be edited as appropriate.

By default, Sqitch will read sqitch.conf in the current directory for settings. But it will also read ~/.sqitch/sqitch.conf for user-specific settings. Since SQLite's sqlite3 client is not in the path on my system, let's go ahead an tell it where to find the client on our computer.

  > sqitch config --user core.sqlite.client /opt/local/bin/sqlite3

And let's also tell it who we are, since this data will be 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
  [core "sqlite"]
        client = /opt/local/bin/sqlite3
  [user]
        name = Marge N. O’Vera
        email = marge@example.com

Which means that Sqitch should be able to find sqlite3 for any project, and that 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-b2
  %project=flipr
  %uri=https://github.com/theory/sqitch-sqlite-intro/

Note that it has 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.

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

  > git add .
  > git commit -am 'Initialize Sqitch configuration.'
  [master 706d2ad] Initialize Sqitch configuration.
   2 files changed, 16 insertions(+)
   create mode 100644 sqitch.conf
   create mode 100644 sqitch.plan

Our First Change ^

Let's create a table. Our app will need users, of course, so we'll create a table for them. Run this command:

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

The add command adds a database change to the plan and writes deploy, revert, and verify scripts that represent the change. Now we edit these files. The deploy script's job is to create the table. By default, the deploy/users.sql file looks like this:

  -- Deploy users

  BEGIN;

  -- XXX Add DDLs here.

  COMMIT;

What we want to do is to replace the XXX comment with the CREATE TABLE statement, like so:

  -- Deploy users

  BEGIN;

  CREATE TABLE users (
          nickname  TEXT      PRIMARY KEY,
          password  TEXT      NOT NULL,
          fullname  TEXT      NOT NULL,
          twitter   TEXT      NOT NULL,
          timestamp DATETIME  NOT NULL DEFAULT CURRENT_TIMESTAMP
  );

  COMMIT;

The revert script's job is to precisely revert the change to the deploy script, so we edit this to revert/users.sql to look like this:

  -- Revert users

  BEGIN;

  DROP TABLE users;

  COMMIT;

Now we can try deploying this change:

  > sqitch --db-name flipr_test.db deploy
  Adding metadata tables to flipr_test-sqitch.db
  Deploying changes to flipr_test.db
        + users .. ok

First Sqitch created the metadata database and tables used to track database changes. This database is separate from the database to which the users change was deployed; by default, it has the same name as the destination database, but with -sqitch appended to the base name. If you'd like it to have a different name, use sqitch config core.sqlite.sqitch_db $name to configure it. This will be especially useful if you use the SQLite ATTACH DATABASE command to manage multiple database files in a single project. In that case, you will want to use the same metadata file for all the databases.

Next, Sqitch deploys changes to the destination database, which we specified on the command-line. We only have one so far; the + 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 schema:

        > sqlite3 flipr_test.db '.tables'
        users

Trust, But Verify

But that's too much work. do you really want to do something like that after every deploy?

Here's where the verify script comes in. Its job is to test that the deploy did was it was supposed to. It should do so without regard to any data that might be in the database, and should throw an error if the deploy was not successful. The easiest way to do that with a table is to simply SELECT from it. Put this query into verify/users.sql:

  SELECT nickname, password, fullname, twitter
        FROM users
   WHERE 0;

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

  > sqitch --db-name flipr_test.db verify
  Verifying flipr_test.db
        * users .. ok
  Verify successful

Looks good! If you want to make sure that the verify script correctly dies if the table doesn't exist, temporarily change the table name in the script to something that doesn't exist, something like:

  SELECT nickname, password, timestamp
        FROM users_nonesuch
   WHERE 0;

Then verify again:

  > sqitch --db-name flipr_test.db verify
  Verifying flipr_test.db
        * users .. Error: near line 5: no such table: users_nonesuch
  # Verify script "verify/users.sql" failed.
  not ok

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

SQLite is kind enough to tell us what the problem is. 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 was recorded via the status command, which reads the tables from the metadata database:

  > sqitch --db-name flipr_test.db status
  # On database flipr_test.db
  # Project:  flipr
  # Change:   5f102a2fcb29a16d1fb958439aac5bacbeac89ac
  # Name:     users
  # Deployed: 2013-04-05 13:16:29 -0700
  # By:       Marge N. O’Vera <marge@example.com>
  #
  Nothing to deploy (up-to-date)

Let's make sure that we can revert the change:

  > sqitch --db-name flipr_test.db revert
  Revert all changes from flipr_test? [Yes]
        - users .. ok

The revert command first prompts to make sure that we really do want to 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:

        > sqlite3 flipr_test.db '.tables'

And the status message should reflect as much:

  > sqitch --db-name flipr_test.db status
  # On database flipr_test.db
  No changes deployed

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

  > sqitch --db-name flipr_test.db verify
  Verifying flipr_test.db
  No changes deployed

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

  > sqitch --db-name flipr_test.db log
  On database flipr_test.db
  Revert 5f102a2fcb29a16d1fb958439aac5bacbeac89ac
  Name:      users
  Committer: Marge N. O’Vera <marge@example.com>
  Date:      2013-04-05 13:18:13 -0700

          Creates table to track our users.

  Deploy 5f102a2fcb29a16d1fb958439aac5bacbeac89ac
  Name:      users
  Committer: Marge N. O’Vera <marge@example.com>
  Date:      2013-04-05 13:16:29 -0700

          Creates table to track our users.

Note that the actions we took are shown in reverse chronological order, with the revert first and then the deploy.

Cool. Let's tell Git to ignore *.db files and then commit it.

  > echo '*.db' > .gitignore
  > git add .
  > git commit -m 'Add users table.'
  [master 1e1d190] Add users table.
   5 files changed, 31 insertions(+)
   create mode 100644 .gitignore
   create mode 100644 deploy/users.sql
   create mode 100644 revert/users.sql
   create mode 100644 verify/users.sql

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

  > sqitch --db-name flipr_test.db deploy --verify
  Deploying changes to flipr_test.db
        + users .. ok

And now the users table should be back:

  > sqlite3 flipr_test.db '.tables'
  users

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

  > sqitch --db-name flipr_test.db status
  # On database flipr_test.db
  # Project:  flipr
  # Change:   5f102a2fcb29a16d1fb958439aac5bacbeac89ac
  # Name:     users
  # Deployed: 2013-04-05 13:20:02 -0700
  # By:       Marge N. O’Vera <marge@example.com>
  #
  Nothing to deploy (up-to-date)

More Configuration ^

I'm getting a little tired of always having to type --db-name flipr_test.db, aren't you? We could use -d instead, but even simpler it to just make that the default. Let's do that, shall we?

  > sqitch config core.sqlite.db_name flipr_test.db

Now we can leave it out, 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.db
  # Project:  flipr
  # Change:   5f102a2fcb29a16d1fb958439aac5bacbeac89ac
  # Name:     users
  # Deployed: 2013-04-05 13:20:02 -0700
  # By:       Marge N. O’Vera <marge@example.com>
  #
  Nothing to deploy (up-to-date)

Yay, that allows things to be a little more concise. Let's also make sure that changes are verified after deploying them:

  > 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 and make some more changes!

  > git commit -am 'Set default DB name and always verify.'
  [master 9428556] Set default DB name and always verify.
   1 file changed, 6 insertions(+)

Deploy with Dependency ^

Let's add another change. Our app will need to store status messages from users. Let's call them -- and the table to store them -- "flips". First, add the new change:

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

Note that we're requiring the users change as a dependency of the new flips change. Although that change has already been added to the plan and therefore should always be applied before the flips change, it's a good idea to be explicit about dependencies.

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

  -- Deploy flips
  -- requires: users

  BEGIN;

  CREATE TABLE flips (
          id        INTEGER   PRIMARY KEY AUTOINCREMENT,
          nickname  TEXT      NOT NULL REFERENCES users(nickname),
          body      TEXT      NOT NULL DEFAULT '' CHECK ( length(body) <= 180 ),
          timestamp DATETIME  NOT NULL DEFAULT CURRENT_TIMESTAMP
  );

  COMMIT;

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

The users.nickname column references the users table.This is why we need to require the users change.

Now for the verify script. Again, all we need to do is SELECT from the table. I recommend selecting each column by name, too, to be sure that no column is missing. Here's the verify/flips.sql:

  -- Verify flips

  BEGIN;

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

  COMMIT;

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

  -- Revert flips

  BEGIN;

  DROP TABLE flips;

  COMMIT;

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

  > sqitch deploy
  Deploying changes to flipr_test.db
        + flips .. 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:

  > sqlite3 flipr_test.db '.tables'
  flips  users

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

  > sqitch verify
  Verifying flipr_test.db
        * users .. ok
        * flips .. ok
  Verify successful

Now have a look at the status:

  > sqitch status
  # On database flipr_test.db
  # Project:  flipr
  # Change:   12a3622b0b54c628de33c40512c049a3ad570ef4
  # Name:     flips
  # Deployed: 2013-04-05 13:22:12 -0700
  # 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 users from flipr_test.db
        - flips .. 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 users, 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 flips table should be gone but the users table should still be around:

  > sqlite3 flipr_test.db '.tables'
  users

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

  > sqitch status
  # On database flipr_test.db
  # Project:  flipr
  # Change:   5f102a2fcb29a16d1fb958439aac5bacbeac89ac
  # Name:     users
  # Deployed: 2013-04-05 13:20:02 -0700
  # By:       Marge N. O’Vera <marge@example.com>
  #
  Undeployed change:
        * flips

As does the verify command:

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

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

Okay, let's commit and deploy again:

  > git add .
  > git commit -am 'Add flips table.'
  [master 5e04f7f] Add flips table.
   4 files changed, 30 insertions(+)
   create mode 100644 deploy/flips.sql
   create mode 100644 revert/flips.sql
   create mode 100644 verify/flips.sql
  > sqitch deploy
  Deploying changes to flipr_test.db
        + flips .. ok

Looks good. Check the status:

  > sqitch status
  # On database flipr_test.db
  # Project:  flipr
  # Change:   12a3622b0b54c628de33c40512c049a3ad570ef4
  # Name:     flips
  # Deployed: 2013-04-05 13:24:07 -0700
  # By:       Marge N. O’Vera <marge@example.com>
  #
  Nothing to deploy (up-to-date)

View to a Thrill ^

One more thing to add before we are ready to ship a first beta release. Let's create a view that lists user names with their flips.

  > sqitch add userflips --requires users --requires flips \
        -n 'Creates the userflips view.'
  Created deploy/userflips.sql
  Created revert/userflips.sql
  Created verify/userflips.sql
  Added "userflips [users flips]" to sqitch.plan

Now add this SQL to deploy/userflips.sql:

  CREATE VIEW userflips AS
  SELECT f.id, u.nickname, u.fullname, f.body, f.timestamp
        FROM users u
        JOIN flips f ON u.nickname = f.nickname;

Add this SQL to verify/userflips.sql

  SELECT id, nickname, fullname, body, timestamp
        FROM userflips
   WHERE 0;

And add the DROP VIEW statement to revert/userflips.sql:

  DROP VIEW userflips;

Now Try it out!

  > sqitch deploy
  Deploying changes to flipr_test.db
        + userflips .. ok
  > sqitch revert -y
  Reverting all changes from flipr_test.db
        - userflips .. ok
        - flips ...... ok
        - users ...... ok
  > sqitch deploy
  Deploying changes to flipr_test.db
        + users ...... ok
        + flips ...... ok
        + userflips .. ok

Looks good! Commit it.

  > git add .
  > git commit -m 'Add the userflips view.'
  [master f76f6e7] Add the userflips view.
   4 files changed, 29 insertions(+)
   create mode 100644 deploy/userflips.sql
   create mode 100644 revert/userflips.sql
   create mode 100644 verify/userflips.sql

Ship It! ^

Now we're ready for the first development release of our app. Let's call it 1.0.0-dev1 Since we want to have it go out with deployments tied to the release, let's tag it:

  > sqitch tag v1.0.0-dev1 -n 'Tag v1.0.0-dev1.'
  Tagged "userflips" with @v1.0.0-dev1
  > git commit -am 'Tag the database with v1.0.0-dev1.'
  [master 2db2775] 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'

We can try deploying to make sure the tag gets picked up like so:

  > sqitch -d flipr_dev.db deploy
  Adding metadata tables to ./flipr_dev-sqitch.db
  Deploying changes to flipr_dev.db
        + users ................... ok
        + flips ................... ok
        + userflips @v1.0.0-dev1 .. ok

Great, both changes were deployed and userflips was tagged with @v1.0.0-dev1. Let's have a look at the status:

  > sqitch -d flipr_dev.db status
  # On database flipr_dev.db
  # Project:  flipr
  # Change:   e98e18dced32f7ee090ea368510f923e538e719a
  # Name:     userflips
  # Tag:      @v1.0.0-dev1
  # Deployed: 2013-04-05 13:36:52 -0700
  # By:       Marge N. O’Vera <marge@example.com>
  #
  Nothing to deploy (up-to-date)

Note the listing of the tag as part of the status message. Now let's bundle everything up for release:

  > sqitch bundle
  Bundling into bundle
  Writing config
  Writing plan
  Writing scripts
        + users
        + flips
        + userflips @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. Let's try deploying it:

  > cd bundle
  > sqitch --db-name flipr_prod.db deploy
  Adding metadata tables to ./flipr_prod-sqitch.db
  Deploying changes to flipr_prod.db
        + users ................... ok
        + flips ................... ok
        + userflips @v1.0.0-dev1 .. ok

Looks much the same as before, eh? Package it up and ship it!

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

Making a Hash of Things ^

Now that we've got the basics of the app done, let's add a feature. Gotta track the hashtags associated with flips, right? Let's add a table for them. But since other folks are working on other tasks in the repository, we'll work on a branch, so we can all stay out of each other's way. So let's branch:

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

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

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

You know the drill by now. Add this to deploy/hashtags.sql

  CREATE TABLE hashtags (
          flip_id   INTEGER   NOT NULL REFERENCES flips(id),
          hashtag   TEXT      NOT NULL CHECK ( length(hashtag) > 0 ),
          PRIMARY KEY (flip_id, hashtag)
  );

Again, select from the table in verify/hashtags.sql:

  SELECT flip_id, hashtag FROM hashtags WHERE 0;

And drop it in revert/hashtags.sql

  DROP TABLE hashtags;

And give it a whirl:

  > sqitch deploy
  Deploying changes to flipr_test.db
        + hashtags .. ok

Look good?

  > sqitch status --show-tags
  # On database flipr_test.db
  # Project:  flipr
  # Change:   6b55f1147898da3b46d3671062486e56fac26827
  # Name:     hashtags
  # Deployed: 2013-04-05 13:44:59 -0700
  # By:       Marge N. O’Vera <marge@example.com>
  #
  # Tag:
  #   @v1.0.0-dev1 - 2013-04-05 13:42:26 -0700 - Marge N. O’Vera <marge@example.com>
  #
  Nothing to deploy (up-to-date)

Note the use of --show tags to show all the deployed tags. Now make it so:

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

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

Emergency

Let's do it:

  > git checkout master
  Switched to branch 'master'
  > git pull
  Updating 2db2775..e210a72
  Fast-forward
   deploy/lists.sql | 13 +++++++++++++
   revert/lists.sql |  7 +++++++
   sqitch.plan      |  2 ++
   verify/lists.sql |  9 +++++++++
   4 files changed, 31 insertions(+)
   create mode 100644 deploy/lists.sql
   create mode 100644 revert/lists.sql
   create mode 100644 verify/lists.sql

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

  > git merge --no-ff hashtags
  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 hashtags branch added changes to the plan. Let's try a different approach.

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

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

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

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

  > git checkout hashtags
  Switched to branch 'hashtags'
  > git rebase master
  > git rebase master
  First, rewinding head to replay your work on top of it...
  Applying: Add hashtags 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 hashtags 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:

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 master
  First, rewinding head to replay your work on top of it...
  Applying: Add hashtags 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

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

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

  users 2013-04-05T20:15:55Z Marge N. O’Vera <marge@example.com> # Creates table to track our users.
  flips [users] 2013-04-05T20:21:23Z Marge N. O’Vera <marge@example.com> # Adds table for storing flips.
  userflips [users flips] 2013-04-05T20:28:13Z Marge N. O’Vera <marge@example.com> # Creates the userflips view.
  @v1.0.0-dev1 2013-04-05T20:36:13Z Marge N. O’Vera <marge@example.com> # Tag v1.0.0-dev1.

  lists [users] 2013-04-05T20:41:21Z Marge N. O’Vera <marge@example.com> # Adds table for storing lists.
  hashtags [flips] 2013-04-05T20:43:26Z Marge N. O’Vera <marge@example.com> # Adds table for storing hashtags.

Note that it has appended the changes from the merged "lists" branch, and then merged the changes from our "hashtags" branch. Test it to make sure it works as expected:

  > sqitch rebase -y
  Reverting all changes from flipr_test.db
        - hashtags ................ ok
        - userflips @v1.0.0-dev1 .. ok
        - flips ................... ok
        - users ................... ok
  Deploying changes to flipr_test.db
        + users ................... ok
        + flips ................... ok
        + userflips @v1.0.0-dev1 .. ok
        + lists ................... ok
        + hashtags ................ ok

Note the use of rebase, which combines a revert and a deploy into a single command. Handy, right? It correctly reverted our changes, and then deployed them all again in the proper order. So let's commit .gitattributes; seems worthwhile to keep that change:

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

Merges Mastered

And now, finally, we can merge into master:

  > git checkout master
  Switched to branch 'master'
  > git merge --no-ff hashtags -n "Merge branch 'hashtags'"
  Merge made by the 'recursive' strategy.
   .gitattributes      |  1 +
   deploy/hashtags.sql | 12 ++++++++++++
   revert/hashtags.sql |  7 +++++++
   sqitch.plan         |  1 +
   verify/hashtags.sql |  7 +++++++
   5 files changed, 28 insertions(+)
   create mode 100644 .gitattributes
   create mode 100644 deploy/hashtags.sql
   create mode 100644 revert/hashtags.sql
   create mode 100644 verify/hashtags.sql

And double-check our work:

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

  users 2013-04-05T20:15:55Z Marge N. O’Vera <marge@example.com> # Creates table to track our users.
  flips [users] 2013-04-05T20:21:23Z Marge N. O’Vera <marge@example.com> # Adds table for storing flips.
  userflips [users flips] 2013-04-05T20:28:13Z Marge N. O’Vera <marge@example.com> # Creates the userflips view.
  @v1.0.0-dev1 2013-04-05T20:36:13Z Marge N. O’Vera <marge@example.com> # Tag v1.0.0-dev1.

  lists [users] 2013-04-05T20:41:21Z Marge N. O’Vera <marge@example.com> # Adds table for storing lists.
  hashtags [flips] 2013-04-05T20:43:26Z Marge N. O’Vera <marge@example.com> # Adds table for storing hashtags.

Much much better, a nice clean master now. And because it is now identical to the "hashtags" branch, we can just carry on. Go ahead and tag it, bundle, and release:

  > sqitch tag v1.0.0-dev2 -n 'Tag v1.0.0-dev2.'
  Tagged "hashtags" with @v1.0.0-dev2
  > git commit -am 'Tag the database with v1.0.0-dev2.'
  [master 1edf584] 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
        + users
        + flips
        + userflips @v1.0.0-dev1
        + lists
        + hashtags @v1.0.0-dev2

Note the use of the --dest-dir option to sqitch bundle. Just a nicer way to create the top-level directory name so we don't have to rename it from bundle.

In Place Changes ^

Well, some folks have been testing the 1.0.0-dev2 release and have demanded that Twitter user links be added to Flipr pages. Why anyone would want to include social network links in an anti-social networking app is beyond us programmers, but we're just the plumbers, right? Gotta go with what Marketing demands. The upshot is that we need to update the userflips view, which is used for the feature in question, to include the Twitter user names.

Normally, modifying views in database changes is a PITA. You have to make changes like these:

  1. Copy deploy/userflips.sql to deploy/userflips_twitter.sql.
  2. Edit deploy/userflips_twitter.sql to drop and re-create the view with the twitter column to the view.
  3. Copy deploy/userflips.sql to revert/userflips_twitter.sql. Yes, copy the original change script to the new revert change.
  4. Add a DROP VIEW statement to revert/userflips_twitter.sql.
  5. Copy verify/userflips.sql to verify/userflips_twitter.sql.
  6. Modify verify/userflips_twitter.sql to include a check for the twiter column.
  7. Test the changes to make sure you can deploy and revert the userflips_twitter change.

But you can have Sqitch do most of the work for you. The only requirement is that a tag appear between the two instances of a change we want to modify. In general, you're going to make a change like this after a release, which you've tagged anyway, right? Well we have, with @v1.0.0-dev2 added in the previous section. With that, we can let Sqitch do most of the hard work for us, thanks to the rework command, which is similar to add:

  > sqitch rework userflips -n 'Adds userflips.twitter.'
  Added "userflips [userflips@v1.0.0-dev2]" to sqitch.plan.
  Modify these files as appropriate:
        * deploy/userflips.sql
        * revert/userflips.sql
        * verify/userflips.sql

Oh, so we can edit those files in place. Nice! How does Sqitch do it? Well, in point of fact, it has copied the files to stand in for the previous instance of the userflips change, which we can see via git status:

  > git status
  # On branch master
  # 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/userflips.sql
  #     modified:   sqitch.plan
  #
  # Untracked files:
  #   (use "git add <file>..." to include in what will be committed)
  #
  #     deploy/userflips@v1.0.0-dev2.sql
  #     revert/userflips@v1.0.0-dev2.sql
  #     verify/userflips@v1.0.0-dev2.sql
  no changes added to commit (use "git add" and/or "git commit -a")

The "untracked files" part of the output is the first thing to notice. They are all named userflips@v1.0.0-dev2.sql. What that means is: "the userflips change as it was implemented as of the @v1.0.0-dev2 tag." These are copies of the original scripts, and thereafter Sqitch will find them when it needs to run scripts for the first instance of the userflips change. As such, it's important not to change them again. But hey, if you're reworking the change, you shouldn't need to.

The other thing to notice is that revert/userflips.sql has changed. Sqitch replaced it with the original deploy script. As of now, deploy/userflips.sql and revert/userflips.sql are identical. This is on the assumption that the deploy script will be changed (we're reworking it, remember?), and that the revert script should actually change things back to how they were before. Of course, the original deploy script won't be idempotent -- that is, able to be applied multiple times without changing the result beyond the initial application. It could be if SQLite supported CREATE OR REPLACE VIEW, but since it doesn't, we will have to edit the script to drop the view before creating it. Or, more simply, it needs to be updated to revert changes back to how they were as-of the deployment of deploy/userflips@v1.0.0-dev2.sql.

Modify deploy/userflips.sql to add the twitter column; in fact, let's also add a DROP VIEW IF EXISTS statement, in case we need to rework this change again in the future:

  @@ -4,8 +4,9 @@

   BEGIN;

  +DROP VIEW IF EXISTS userflips;
   CREATE VIEW userflips AS
  -SELECT f.id, u.nickname, u.fullname, f.body, f.timestamp
  +SELECT f.id, u.nickname, u.fullname, u.twitter, f.body, f.timestamp
         FROM users u
         JOIN flips f ON u.nickname = f.nickname;

Next, modify verify/userflips.sql to check for the twitter column. Here's the diff:

  @@ -2,7 +2,7 @@

   BEGIN;

  -SELECT id, nickname, fullname, body, timestamp
  +SELECT id, nickname, fullname, twitter, body, timestamp
         FROM userflips
        WHERE 0;

And finally, modify deploy/userflips@v1.0.0-dev2.sql to drop the view before creating it:

  @@ -4,6 +4,7 @@

   BEGIN;

  +DROP VIEW IF EXISTS userflips;
   CREATE VIEW userflips AS
   SELECT f.id, u.nickname, u.fullname, f.body, f.timestamp
         FROM users u

Note that if we had included that statement when we originally created the userflips change, we wouldn't have to change this file at all.

Now try a deployment:

  > sqitch deploy
  Deploying changes to flipr_test.db
        + userflips .. ok

So, are the changes deployed?

  > sqlite3 flipr_test.db '.schema userflips'
  CREATE VIEW userflips AS
  SELECT f.id, u.nickname, u.fullname, u.twitter, f.body, f.timestamp
        FROM users u
        JOIN flips f ON u.nickname = f.nickname;

Awesome, the view now includes the twitter column. But can we revert?

  > sqitch revert --to @HEAD^ -y
  Reverting changes to hashtags @v1.0.0-dev2 from flipr_test.db
        - userflips .. ok

Did that work, is the twitter column gone?

  > sqlite3 flipr_test.db '.schema userflips'
  CREATE VIEW userflips AS
  SELECT f.id, u.nickname, u.fullname, f.body, f.timestamp
        FROM users u
        JOIN flips f ON u.nickname = f.nickname;

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

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

  > git add .
  > git ci -m 'Add the twitter column to the userflips view.'
  [master 23b46a8] Add the twitter column to the userflips view.
   7 files changed, 40 insertions(+), 4 deletions(-)
   create mode 100644 deploy/userflips@v1.0.0-dev2.sql
   create mode 100644 revert/userflips@v1.0.0-dev2.sql
   create mode 100644 verify/userflips@v1.0.0-dev2.sql

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>

License ^

Copyright (c) 2012-2013 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.

syntax highlighting: