Monday, October 12, 2009

Version control of database objects

To ease the pain of keeping version control of database objects I created a nAnt script for synching stored procs, triggers, functions and views. Using sql server 2008 (but earlier versions are good too, but you may need to change some element types (see script-files) to make it work), TFS and standard scripting.

What happens?
1. the nant-build will process SPs, Views, Functions and Triggers. (but not Tables, table contents and SSIS as this requires some more work)
2. It asks the database about the objects (e.g. all SPs) and their ids
3. It stores the result as a csv-file with "objectName, objectID" format (in file "scriptResult.txt").
4. It goes through each pair and fetches the CREATE-script for each objectID in the database
5. It creates a file with name: [objectName].sql and places it in a folder according to type
6. It then removes all files in [workspace]/dev/database/[object type] and copies the created scripts over
7. It then calls tfpt to synch what is added, deleted and edited (the changelist is connected to the user who ran the script)

NOTE:
1. The db connection is set to be "trusted" (using your windows auth). But as the scripts use osql/bcp it is easy to change this to db-credentials.
2. The script only supports a dev-branch (should be easy to extend).

The scripts:
All of it in a zip (so that you do not need to wait unnecessary...)
Each file, with description:
  1. This starts the whole thing, it just calls a nAnt with the correct target
    RunTFSSynchOfDBObjects.cmd
  2. This runs through all the supported objects to backup
    FetchDBObjectsAndGetScripts.build
  3. Each target in the nAnt in step 2. calls this script to fetch object name and id (puts it in the "scriptResults.txt" file), you'll need to change the db-server and db-name in this one:
    FetchObjectsAndIdsGivenAnObjectType.cmd
  4. Each target in the nAnt in step 2. goes through the "scriptResults.txt" (the csv-file) and then calls
    GetScriptForObject.cmd
    to get the sql script for the current "objectName, objectID". You'll need to change the db-server name in this one. Note; this uses bcp (bulk copy) as some db-object-scripts are too large for osql.
  5. The nAnt in step 2. then calls script for copying result files to your TFS workfolder, synching with TFS and adding changes to your "pending changes" list. Note; you'll need to refresh the "pending changes" list if source control GUI is currently open. In the script
    CheckOutScriptFilesAndReplaceWithNewContent.cmd
    you'll need to set your workfolder. Follow instructions in the file.