对于数据项目来说,编写Sql是一项基本任务同时也是数量最多的代码。为了统一项目代码规范同时降低Code Review的成本,因此需要通过自动化的方式来进行规则校验。由于本人所在的项目以SQL Server数据库为基础,于是本人决定通过使用SqlScriptDom类库来做T-SQL的规则校验。如果是其他数据库项目,则可采用ANTLR库做规则校验,其实现的方式大体一致。
SqlScriptDom是针对SQL Server的.Net的类库,由微软公司开发并开源,源码地址 。有兴趣的朋友可以去研究一下。其次项目采用Powershell来开发,有以下原因
- 使用脚本开发比较灵活,不用编译,开发即可部署。
- Powershell可以直接使用.Net类库,并且具有高级语言的一些特点方便开发。
项目使用VS Code作为开发调试工具,需要安装Powershell相关的插件。由于要使用到PowerShell的自定义类来开发,所以需要提前将类库加载到Powershell中,因此需要配置Powershell的环境。如何配置环境可以参考这篇文章,介绍如何创建和使用 PowerShell 配置文件。并通过Add-Type这个命令来加载它。
以下是具体代码
using namespace Microsoft.SqlServer.TransactSql.ScriptDom using namespace System using namespace System.Collections.Generic using namespace System.IO using namespace Management.Automation using namespace System.Reflectionenum Severity {Information = 1Warning = 2Exception = 3Fault = 4 }enum ResponseCode {Success = 0Exception = 10001ParseError = 10002 }
using namespace Microsoft.SqlServer.TransactSql.ScriptDom
这句是使用了命名空间,后面在使用相关对象时候无需采用完全限定名,从而简化代码。随后定义了两个枚举,Severity定义规则的严重程度,ResponseCode定义在程序处理过程中的各种状态。
下面定义CustomerParser类,该类的功能是接收输入的Sql代码,通过语法和词法分析后生成相关语法树,再对语法树进行分析,从而判断代码中哪些片段是违反了项目的编码规则,从而达到Code Review的作用。
class CustomParser {hidden [TSqlParser] $TSqlParserhidden [TSqlFragment]$Treehidden $AnalysisCodeSummary = [PSCustomObject]([ordered]@{ResponseCode = [ResponseCode]::Success;ResponseMessage = "Success";FileName = $null;DocumentName = $null;Code = $null;IsDocument = $true;ParseErrors = [List[ParseError]]::new();ValidationResults = [List[psobject]]::new();})hidden [bool] $IsDocumenthidden [string] $FileNamehidden [string] $Codehidden CustomParser([SqlVersion]$version, [SqlEngineType]$engineType) {switch ($version) {[SqlVersion]::Sql120 { $this.TSqlParser = [TSql120Parser]::new($true) }[SqlVersion]::Sql130 { $this.TSqlParser = [TSql130Parser]::new($true, $engineType) }[SqlVersion]::Sql140 { $this.TSqlParser = [TSql140Parser]::new($true, $engineType) }[SqlVersion]::Sql150 { $this.TSqlParser = [TSql150Parser]::new($true, $engineType) }Default { $this.TSqlParser = [TSql160Parser]::new($true, $engineType) }}}hidden [void] Parse() {$this.AnalysisCodeSummary.FileName = $this.FileName$this.AnalysisCodeSummary.IsDocument = $this.IsDocument $this.AnalysisCodeSummary.DocumentName = [Path]::GetFileName($this.FileName)[StringReader]$reader = $null[ParseError[]]$errors = @() try {if ($this.IsDocument) { $this.Code = [File]::ReadAllText($this.FileName) }$this.AnalysisCodeSummary.Code = $this.Code$reader = [StringReader]::new($this.Code) $this.Tree = $this.TSqlParser.Parse($reader, [ref] $errors)}catch {$this.AnalysisCodeSummary.ResponseCode = [ResponseCode]::Exception$this.AnalysisCodeSummary.ResponseMessage = $_.Exception.Message return}finally {if ($null -ne $reader) { $reader.Close() }}if ($errors.Count -ne 0) {$this.AnalysisCodeSummary.ResponseCode = [ResponseCode]::ParseError$this.AnalysisCodeSummary.ResponseMessage = "An error occurred while parsing the code."$this.AnalysisCodeSummary.ParseErrors = $errors}}hidden [void]Validate([BaseRule] $rule, [bool]$lockRule) {[psobject]$validationResult = [PSCustomObject]([ordered]@{ResponseCode = [ResponseCode]::Success;ResponseMessage = "Success";RuleName = $rule.RuleName;Descrtiption = $rule.Descrtiption;Severity = $rule.Severity;Validated = $true;AnalysisCodeResults = @();})$lockTaken = $falsetry {if ($lockRule) { [Threading.Monitor]::Enter($rule.AnalysisCodeResults, [ref] $lockTaken) }$rule.AnalysisCodeResults = @()$this.Tree.Accept($rule)$validationResult.AnalysisCodeResults += $rule.AnalysisCodeResults}catch {$validationResult.ResponseCode = [ResponseCode]::Exception$validationResult.ResponseMessage = $_.Exception.Messagereturn}finally {if ($lockTaken) { [Threading.Monitor]::Exit($rule.AnalysisCodeResults) }$validationResult.Validated = $validationResult.ResponseCode -eq [ResponseCode]::Success `-and (( $validationResult.AnalysisCodeResults | Where-Object { -not $_.Validated } ).Count -eq 0)if (-not $validationResult.Validated) {$this.AnalysisCodeSummary.ValidationResults += $validationResult} }}static [psobject] Analysis([string]$codeOrFile, [bool]$isDocumnet, [BaseRule[]]$rules) {[CustomParser]$parser = [CustomParser]::new([SqlVersion]::Sql130, [SqlEngineType]::All)if (-not $isDocumnet) { $parser.Code = $codeOrFile }else { $parser.FileName = $codeOrFile }$parser.IsDocument = $isDocumnet$parser.Parse()if ($parser.AnalysisCodeSummary.ResponseCode -eq [ResponseCode]::Success) {foreach ($rule in $rules) {$parser.Validate($rule, $false)}}return $parser.AnalysisCodeSummary}static [psobject[]] Analysis([string[]]$files, [BaseRule[]]$rules) {$result = @()foreach ($file in $files) { $result += [CustomParser]::Analysis($file, $true, $rules) }return $result}
}
hidden [TSqlParser] $TSqlParser
该变量是T-SQL的分析器,通过该变量的Parse方法将SQL解析成语法树,hidden表示该变量仅在类内部使用。
hidden [TSqlFragment]$Tree
该变量则存储分析后的语法树。
hidden $AnalysisCodeSummary = [PSCustomObject]([ordered]@{ResponseCode = [ResponseCode]::Success;ResponseMessage = "Success";FileName = $null;DocumentName = $null;Code = $null;IsDocument = $true;ParseErrors = [List[ParseError]]::new();ValidationResults = [List[psobject]]::new();})
该变量是存储语法分析和规则分析的结果。
ParseErrors列表存储的是当语法分析出错时的错误结果。ValidationResults列表则存储的是每条规则校验后的结果。
hidden CustomParser([SqlVersion]$version, [SqlEngineType]$engineType) {switch ($version) {[SqlVersion]::Sql120 { $this.TSqlParser = [TSql120Parser]::new($true) }[SqlVersion]::Sql130 { $this.TSqlParser = [TSql130Parser]::new($true, $engineType) }[SqlVersion]::Sql140 { $this.TSqlParser = [TSql140Parser]::new($true, $engineType) }[SqlVersion]::Sql150 { $this.TSqlParser = [TSql150Parser]::new($true, $engineType) }Default { $this.TSqlParser = [TSql160Parser]::new($true, $engineType) }}}
CustomParser类的构造函数,$version定的时使用那个版本的分析器,比如Sql130就对应Sql Server2016,$engineType参数定义了使用哪种引擎,是Sql Server还是Azure亦或两者都采用。
CustomParser类中的Parse方法是做语法分析的。Validate方法则是做规则校验,该方法的$rule参数是传入的各种验证规则,均继承自BaseRule类。$lockRule是当采用多线程执行时是否加锁来保证结果完整。
下面则是BaseRule的代码。
class BaseRule:TSqlFragmentVisitor {[string]$Descrtiption[Severity]$Severity = [Severity]::Information$AnalysisCodeResults = @()[string]$RuleName = $this.GetType().Namehidden [string] $Additionalhidden [void] Validate([TSqlFragment] $node, [bool] $validated , [string] $addtional) {$this.AnalysisCodeResults += [BaseRule]::GetAnalysisResult($node, $validated, $addtional)}static [BaseRule[]] GetAllRules() {return [Assembly]::GetAssembly([BaseRule]).GetTypes() `| Where-Object { $_ -ne [BaseRule] -and $_.BaseType -eq [BaseRule] } `| ForEach-Object { New-Object $_ }}static [psobject] GetAnalysisResult([TSqlFragment] $node, [bool] $validated , [string] $addtional) {return [PSCustomObject]([ordered]@{StartLine = $node.StartLine;EndLine = if ($node.LastTokenIndex -gt 0) { $node.ScriptTokenStream[$node.LastTokenIndex].Line } else { $node.LastTokenIndex }StartColumn = $node.StartColumn;Validated = $validated;Text = if ($node.FragmentLength -gt 0) `{ $node.ScriptTokenStream[$node.FirstTokenIndex..$node.LastTokenIndex].Text -join [string]::Empty } `else { $null }Additional = $addtional })}
}
它继承自TSqlFragmentVisitor,Validate方法用来解析被规则命中的语法节点,并记录该节点在代码中的详情,如该节点在代码中的开始行,结束行,命中的文本等,方便修改相关的SQL代码。同时将这些记录添加到AnalysisCodeResults列表,并将该列表的数据添加到CustomParser类中的ValidationResults列表中。具体规则通过重写基类的Visit方法来实现代码分析。此外还定义了一个静态方法GetAllRules用以获取项目中所有的规则。以上便是整个项目的核心代码,下面将介绍一些具体样例。
我们先做一个简单的例子,比如我们规定在Select中不能包含星号(*)。代码如下:
class PDE001: BaseRule {PDE001() {$this.Descrtiption = "Asterisk in select list."$this.Severity = [Severity]::Warning}[void] Visit([SelectStarExpression] $node) {$this.Validate($node, $false, $null)}
}
够简单了吧,首先继承自BaseRule类,然后重写Visit方法。由于Visit被重载了很多,我们选择参数类型为SelectStarExpression的方法,当语法树中存在这个节点的时候,我们调用基类的$this.Validate($node, $false, $null)方法,并记录了该节点的详情,这样就代表Sql代码没能通过该条规则。
比如我们写下这样一条Sql,Select * from test;然后通过调用来看下执行结果。
接下来我再讲一条比较复杂的规则。比如我们在做数据操作的时,为了降低对资源的占用时间。我们不能直接插入,删除或者更新大批量数据,这是就需要将数据分成小批量,然后通过循环的方式来处理。为了防止这样的代码,我们需要制定该规则。当然该规则也会有一些特例,如被处理的对象是表变量或者临时表,则可以忽略该规则。以下是该规则的代码实现
class PDE003:BaseRule {PDE003() {$this.Descrtiption = "You should use batch operations in statements."$this.Severity = [Severity]::Exception}hidden [int]$start = 0hidden [int]$end = 0[void] Visit([UpdateDeleteSpecificationBase]$node) {$target = $node.Targetif ($target -is [VariableTableReference]) { return }if ($this.CheckWhile($node)) { return }[NamedTableReference] $namedTableReference = $target -as [NamedTableReference]$targetTable = $namedTableReference.SchemaObject.BaseIdentifier.Valueif ($targetTable -imatch "^#{1,2}") { return }$fromClause = $node.FromClauseif ($null -ne $fromClause) {[TemporaryTableVisitor]$tempVisitor = [TemporaryTableVisitor]::new($fromClause, $targetTable)$fromClause.AcceptChildren($tempVisitor)if ($tempVisitor.Validated) { return }}$this.Validate($node, $false, $null)}[void] Visit([InsertSpecification]$node) {$target = $node.Targetif ($target -is [VariableTableReference]) { return }if ($this.CheckWhile($node)) { return }$namedTableReference = $target -as [NamedTableReference]if ($namedTableReference.SchemaObject.BaseIdentifier.Value -imatch "^#{1,2}") { return }$valuesInsertSource = $node.InsertSource -as [ValuesInsertSource]if ($null -ne $valuesInsertSource) { return }$this.Validate($node, $false, $null)}[void] Visit([MergeSpecification]$node) {$target = $node.Targetif ( $this.CheckWhile($node)) { return }if ($target -is [VariableTableReference]) { return }$namedTableReference = $target -as [NamedTableReference]if ($namedTableReference.SchemaObject.BaseIdentifier.Value -imatch "^#{1,2}") { return }$this.Validate($node, $false, $null)}[void] Visit([WhileStatement]$node) {$this.start = $node.StartLine$this.end = $node.ScriptTokenStream[$node.LastTokenIndex].Line}hidden [bool] CheckWhile([TSqlFragment] $node) {return $node.StartLine -ge $this.start -and $node.ScriptTokenStream[$node.LastTokenIndex].Line -le $this.end}
}class TemporaryTableVisitor:TSqlFragmentVisitor {[bool]$Validated = $falsehidden [string] $pattern = "^(@|#{1,2})"hidden [FromClause]$fromClausehidden [string]$targetTemporaryTableVisitor([FromClause]$fromClause, [string]$target) {$this.fromClause = $fromClause$this.target = $targetif ($null -eq $fromClause) { $this.Validated = $true }}[void] Visit([NamedTableReference]$node) {$tableName = $node.SchemaObject.BaseIdentifier.Value$alias = $node.Alias.Valueif ($this.target -in $alias, $tableName) {$this.Validated = $this.Validated -or ($tableName -imatch $this.pattern)} }[void] Visit([VariableTableReference]$node) {$tableName = $node.Variable.Name$alias = $node.Alias.Valueif ($this.target -in $alias, $tableName) {$this.Validated = $this.Validated -or ($tableName -imatch $this.pattern)} }
}
该类还引用了另外一个辅助类,辅助类是处理当前节点为Insert、Update、Delete语句的时候,获取该语句中的FROM节点中的表对象,并判断该表是否属于临时表或者表变量,如果是则忽略该规则。
当直接输入 DELETE A FROM TEST1 A INNER JOIN TEST2 B ON A.ID=B.ID,我们可以看到规则阻挡了该语句,这时Validated属性为false。
当我们代码变成 DELETE A FROM #TEST1 A INNER JOIN TEST2 B ON A.ID=B.ID,我们看到规则通过了该段代码,且Validated属性为true。
当我们在DELETE A FROM TEST1 A INNER JOIN TEST2 B ON A.ID=B.ID 语句加上WHILE再看下呢,恭喜通过了该规则的验证。
以下是客户端调用的代码
using module '.\Code Analysis\Rule.psm1'$files = Get-ChildItem -Path "E:\BackupE\QueryFile" -Filter "*.sql" -File
$rules = [BaseRule]::GetAllRules()
$result = [CustomParser]::Analysis($files.FullName, $rules)
$result.Where({ $_.ResponseCode -eq [ResponseCode]::Success -and $_.ValidationResults.Where({ -not $_.Validated }).Count -gt 0 }) |`Select-Object -Property FileName, DocumentName -ExpandProperty ValidationResults |`Select-Object -ExpandProperty AnalysisCodeResults -ExcludeProperty Validated , AnalysisCodeResults
自此,整个代码就介绍完了,如果需要代码的话可以到以转到以下地址(下载地址)。前文提到的用ANTLR去做Code Analysis的话,需要自己去维护语法文档(文档地址),此外还需相关的工具将语法文件生成语法分析库然后调用即可。