Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

SQL Code Analysis From a PowerShell Deployment Script

DZone's Guide to

SQL Code Analysis From a PowerShell Deployment Script

See this tutorial to learn how to automate static code analysis on a database.

· Database Zone ·
Free Resource

New whitepaper: Database DevOps – 6 Tips for Achieving Continuous Delivery. Discover 6 tips for continuous delivery with Database DevOps in this new whitepaper from Redgate. In 9 pages, it covers version control for databases and configurations, branching and testing, automation, using NuGet packages, and advice for how to start a pioneering Database DevOps project. Also includes further research on the industry-wide state of Database DevOps, how application and database development compare, plus practical steps for bringing DevOps to your database. Read it now free.

Database code analysis becomes more important as the team doing the database development gets bigger and more diverse in skills. Hard-working database developers sometimes check-in "temporary" development code by mistake, so it is always good to have a way of flagging up SQL Code issues and "smells" that are agreed to be incompatible with "production" standards.

Database Developers like to agree and share a common set of styles and conventions so that they can work easily on all parts of the database code. Where the developers need to work across applications rather than just on the database, these pre-release checks on the source become even more important because these checks should indicate where code review might be helpful. SQL Code Guard can work with either a database or the source code.

We all have different views of what constitutes best-practice, so SQL Code Guard allows the team full control over what gets checked and what is ignored. The most important aspect of checking on code is to ensure consistency. The team needs to be able to share settings easily and change them when necessary. Code analysis settings are best kept in source control with the version.

Automating Static Code Analysis on a Database

SQL Code Guard's static code analysis rules are now built-in to SQL Prompt so that developers can usually avoid checking in suspect code. The command-line version of SQL Code Guard can read the code analysis settings from SQL Prompt and can be used simply in PowerShell. This means that SQL Change Automation and any other PowerShell-based process can be adapted to run automated SQL code analysis.

Delivery teams can create and share a configuration file, defining which rules to include or exclude for development and build tests so that the report that is generated reflects, consistently, the current development standards.

The current command-line version of SQL Code Guard can be downloaded from the Redgate site as a ZIP file and should be installed in a directory with all the files together. As long as the command-line version is fully-referenced by its path, it should work fine.

Listing 1 shows a simple way of using SQL Code Guard in PowerShell to check a live database. You will, of course, need to fill in the correct values of the parameters. Be careful, also, to ensure that your Windows user has rights to create a file at the outfile destination.

Set-Alias CodeGuard 'PathToCodeguard\SqlCodeGuard30.Cmd.exe' 
  $params = @{
  server='MyServerName' #The server name to connect
  Database='MyDatabase' #The database name to analyze
  user='MyUserName' # If no user specified then Windows authentication will be used so delete if you use Windows Athentication
  password='MyPassword' #user password. Delete if you use Windows Athentication
  outfile = 'MyPathAndFile.xml' #The file name in which to store the analysis xml report
  exclude='BP007;DEP004;ST001' #A semicolon separated list of rule codes to exclude
  include='all' #A semicolon separated list of rule codes to include
  }
  $result=codeguard @params
  if ($result -imatch 'error') {write-warning $result}

Listing 1

I'll show in a moment how to view the resulting XML file, containing the code analysis findings.

Automating Static Code Analysis on Source Code

You can check the code in any SQL file in any database build script (.sql file) or directory with .sql files in it. Here is a typical format of source control directory, but any directory structure is okay, as it will be searched recursively for any .sql file.

The PowerShell code is even simpler, as there are fewer parameters.

Set-Alias CodeGuard 'PathToCodeguard\SqlCodeGuard30.Cmd.exe' 
  $params = @{
  source='PathToDirectory' #The path to file or folder with /scripts (*.sql) to analyze
  outfile = 'MyPathAndFile.xml' #The file name in which to store the analysis xml report
  exclude='BP007;DEP004;ST001'#A semicolon separated list of rule codes to exclude
  include='all'#A semicolon separated list of rule codes to include
  }
  $result=codeguard @params

  if ($result -imatch 'error') {write-warning $result}

Listing 2

Using a Code Analysis Configuration File From SQL Prompt

If you are using the code analysis feature of SQL Prompt, you can use it to save the code analysis rules settings into a configuration file.

Within SSMS, select Manage Code Analysis rules from the SQL Prompt menu, configure which rules you want enabled or disabled, and then save your settings by clicking Save as..., changing the file location to a shared folder and clicking Save. You can also save the configuration file from the Code Guard add-in for Visual Studio. The UI saves it in %APPDATA%\SqlCodeGuard.Addin\settingsv3.xml.

Listing 3 shows the PowerShell to view the configuration file to get a list of what is being checked and what isn't.

[xml]$XmlSettings = Get-Content -Path 'PathToSettingsFile/.casettings'
  $XmlSettings.SqlCodeGuardSettings.IssueSettings

Listing 3

You use your XML configuration file with either a database or source code.

$params = @{
  source='PathToDirectory' #The path to file or folder with /scripts (*.sql) to analyze
  config='PathToSettingsFile/.casettings' #The rules settings file to use 
  outfile = 'MyPathAndFile.xml' #The file name in which to store the analysis xml report
  }
  $result=codeguard @params

  if ($result -imatch 'error') {write-warning $result}

Listing 4

Viewing the XML File

So far so good, but the result is an XML file. There are plenty of ways of viewing it once you can get it into a table. Listing 5 shows one way to do that.

[xml]$XmlDocument = Get-Content -Path 'MyPathAndFile.xml'
  $XmlDocument.root.GetEnumerator() |foreach{
      $name=$_.name.ToString();
      $_.issue} |
       select-object  @{Name="Object"; Expression = {$name}},
                      code,line,column,text|format-table

Listing 5

Which will give something like this:

As this is scripted, there are plenty of ways of making the reporting side as elaborate as you wish, even sending email reports, the destination of which is based on the name of the object. You can even use PowerShell to attach the relevant report to the SQL script file as a block comment if you have a consistent file-naming convention that is based on the name of the object.

The output of the program has interesting information such as the number of code-smells being searched, but the only word we are looking for in this example is "Error." There is also a log file that can be stored with the documentation of the build.

Conclusions

Currently, the command-line version of SQL Code Guard is free to use, subject to the license conditions. It provides a good way of checking the code of any SQL Server database development as part of a continuous delivery. It integrates with other Redgate products. It can, for example, use the code analysis checks, as determined by the development team using SQL Prompt. It is easy to use as part of a DevOps toolchain. More than anything, though, I like it because it is a great way of saving me from embarrassment!

New whitepaper: Database DevOps – 6 Tips for Achieving Continuous Delivery. Discover 6 tips for continuous delivery with Database DevOps in this new whitepaper from Redgate. In 9 pages, it covers version control for databases and configurations, branching and testing, automation, using NuGet packages, and advice for how to start a pioneering Database DevOps project. Also includes further research on the industry-wide state of Database DevOps, how application and database development compare, plus practical steps for bringing DevOps to your database. Read it now free.

Topics:
database ,sql ,code analysis

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}