Skip to content

Commit

Permalink
Merge pull request #73 from webmd-health-services/bugfix/schema.ps1-n…
Browse files Browse the repository at this point in the history
…ot-run

Fixed: baseline schema.ps1 not getting run when pushing
  • Loading branch information
splatteredbits authored Apr 18, 2024
2 parents f2b6d50 + 7267481 commit a01fbb8
Show file tree
Hide file tree
Showing 59 changed files with 2,811 additions and 2,000 deletions.
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,25 @@

# Rivet Changelog

## 0.23.0

### Changed

* `Export-Migration` no longer includes owner information when it exports `Add-Schema` operations (i.e. the `Owner`
parameter is omitted). When exporting a schema to DDL in SQL Server Management Studio, the owner information is also
omitted so we think this change should be OK.
* Pushing to a database will now apply the baseline schema if it hasn't been applied.

### Fixed

* Baseline schema in schema.ps1 doesn't get applied when pushing migrations.
* The `DropDatabase` command fails if the database name has non alphanumeric characters in its name.

### Removed

Removed the `InitializeSchema` switch from `rivet.ps1` and `Invoke-Rivet` as it was not actually implemented.


## 0.22.0

> Released 6 Jul 2023
Expand Down
18 changes: 10 additions & 8 deletions Rivet/Functions/Columns/New-DateColumn.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,11 @@ function New-DateColumn
Demonstrate show to create a nullable, sparse `date` column when adding a new table.
.EXAMPLE
Add-Table 'Members' { Date 'Birthday' -NotNull -Default 'get`date`()' }
Demonstrates how to create a `date` column with a default value, in this case the current `date`. (You alwyas use UTC `date`s, right?) Probably not a great example, setting someone's birthday to the current `date`. Reasons are left as an exercise for the reader.
Add-Table 'Members' { Date 'Birthday' -NotNull -Default 'getdate()' }
Demonstrates how to create a `date` column with a default value, in this case the current `date`. (You alwyas use
UTC dates, right?) Probably not a great example, setting someone's birthday to the current `date`. Reasons are
left as an exercise for the reader.
.EXAMPLE
Add-Table 'Members' { Date 'Birthday' -Description 'The members birthday.' }
Expand All @@ -49,16 +51,16 @@ function New-DateColumn
# Store nulls as Sparse.
[switch]$Sparse,

# A SQL Server expression for the column's default value
# A SQL Server expression for the column's default value
[String]$Default,

# The name of the default constraint for the column's default expression. Required if the Default parameter is given.
[String]$DefaultConstraintName,

# A description of the column.
[String]$Description
)

switch ($PSCmdlet.ParameterSetName)
{
'Nullable'
Expand All @@ -70,12 +72,12 @@ function New-DateColumn
}
[Rivet.Column]::Date($Name, $nullable, $Default, $DefaultConstraintName, $Description)
}

'NotNull'
{
[Rivet.Column]::Date($Name, [Rivet.Nullable]::NotNull, $Default, $DefaultConstraintName, $Description)
}
}
}

Set-Alias -Name 'Date' -Value 'New-DateColumn'
41 changes: 26 additions & 15 deletions Rivet/Functions/Convert-FileInfoToMigration.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,19 @@ function Convert-FileInfoToMigration
$pluginParameter = @{ Migration = $Migration ; Operation = $_ }

[Rivet.Operations.Operation[]]$operations = & {
Invoke-RivetPlugin -Session $Session `
-Event ([Rivet.Events]::BeforeOperationLoad) `
-Parameter $pluginParameter
if (-not $Migration.IsRivetMigration)
{
Invoke-RivetPlugin -Session $Session `
-Event ([Rivet.Events]::BeforeOperationLoad) `
-Parameter $pluginParameter
}
$operationItem
Invoke-RivetPlugin -Session $Session `
-Event ([Rivet.Events]::AfterOperationLoad) `
-Parameter $pluginParameter
if (-not $Migration.IsRivetMigration)
{
Invoke-RivetPlugin -Session $Session `
-Event ([Rivet.Events]::AfterOperationLoad) `
-Parameter $pluginParameter
}
} |
Where-Object { $_ -is [Rivet.Operations.Operation] } |
Repair-Operation
Expand All @@ -73,16 +79,14 @@ function Convert-FileInfoToMigration
}
}

function Clear-Migration
function Clear-MigrationFunction
{
('function:Push-Migration','function:Pop-Migration') |
Where-Object { Test-Path -Path $_ } |
Remove-Item -WhatIf:$false -Confirm:$false
}

Clear-Migration

Import-RivetPlugin -Path $Session.PluginPaths -ModuleName $Session.PluginModules
Clear-MigrationFunction
}

process
Expand All @@ -94,7 +98,11 @@ function Convert-FileInfoToMigration
Connect-Database -Session $Session -Name $dbName

$m = [Rivet.Migration]::New($fileInfo.MigrationID, $fileInfo.MigrationName, $fileInfo.FullName, $dbName)
$m | Add-Member -Name 'IsRivetMigration' -MemberType NoteProperty -Value $fileInfo.IsRivetMigration
foreach ($noteProperty in ($fileInfo | Get-Member -MemberType NoteProperty))
{
$propertyName = $noteProperty.Name
$m | Add-Member -Name $propertyName -MemberType NoteProperty -Value ($fileInfo.$propertyName)
}

Write-Timing -Message ('Convert-FileInfoToMigration {0}' -f $m.FullName)

Expand Down Expand Up @@ -146,15 +154,18 @@ Pop-Migration function not found. All migrations are required to have a Pop-Migr

$afterMigrationLoadParameter = @{ Migration = $m }
& {
Invoke-RivetPlugin -Session $Session `
-Event ([Rivet.Events]::AfterMigrationLoad) `
-Parameter $afterMigrationLoadParameter
if (-not $m.IsRivetMigration)
{
Invoke-RivetPlugin -Session $Session `
-Event ([Rivet.Events]::AfterMigrationLoad) `
-Parameter $afterMigrationLoadParameter
}
}
$m | Write-Output
}
finally
{
Clear-Migration
Clear-MigrationFunction
}
}
}
Expand Down
18 changes: 10 additions & 8 deletions Rivet/Functions/Export-Migration.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,19 @@ function Export-Migration
[Parameter(Mandatory)]
[String] $Database,

# The names of the objects to export. Must include the schema if exporting a specific object. Wildcards supported.
# The names of the objects to export. Must include the schema if exporting a specific object. Wildcards
# supported.
#
# The default behavior is to export all non-system objects.
[String[]] $Include,

# The names of any objects *not* to export. Matches the object name *and* its schema name, i.e. `schema.name`. Wildcards supported.
# The names of any objects *not* to export. Matches the object name *and* its schema name, i.e. `schema.name`.
# Wildcards supported.
[String[]] $Exclude,

# Any object types to exclude.
[ValidateSet('CheckConstraint','DataType','DefaultConstraint','ForeignKey','Function','Index','PrimaryKey','Schema','StoredProcedure','Synonym','Table','Trigger','UniqueKey','View','XmlSchema')]
[ValidateSet('CheckConstraint','DataType','DefaultConstraint','ForeignKey','Function','Index','PrimaryKey',
'Schema','StoredProcedure','Synonym','Table','Trigger','UniqueKey','View','XmlSchema')]
[String[]] $ExcludeType,

[Switch] $NoProgress,
Expand Down Expand Up @@ -146,7 +149,6 @@ function Export-Migration
'View' = 'VIEW';
}


function ConvertTo-SchemaParameter
{
param(
Expand Down Expand Up @@ -875,10 +877,10 @@ from
$allColumns = $indexColumnsByObjectID[$Object.object_id] | Where-Object { $_.index_id -eq $Object.index_id }

$includedColumns = $allColumns | Where-Object { $_.is_included_column } | Sort-Object -Property 'name' # I don't think order matters so order them discretely.
$include = ''
$idxInclude = ''
if( $includedColumns )
{
$include = ' -Include ''{0}''' -f (($includedColumns | Select-Object -ExpandProperty 'name') -join ''',''')
$idxInclude = ' -Include ''{0}''' -f (($includedColumns | Select-Object -ExpandProperty 'name') -join ''',''')
}

$columns = $allColumns | Where-Object { -not $_.is_included_column } | Sort-Object -Property 'key_ordinal'
Expand All @@ -893,7 +895,7 @@ from
$columnNames = $columns | Select-Object -ExpandProperty 'name'
Write-ExportingMessage -Schema $Object.schema_name -Name $Object.name -Type Index
$schema = ConvertTo-SchemaParameter -SchemaName $Object.schema_name
' Add-Index{0} -TableName ''{1}'' -ColumnName ''{2}'' -Name ''{3}''{4}{5}{6}{7}{8}' -f $schema,$Object.table_name,($columnNames -join ''','''),$Object.name,$clustered,$unique,$include,$descending,$where
' Add-Index{0} -TableName ''{1}'' -ColumnName ''{2}'' -Name ''{3}''{4}{5}{6}{7}{8}' -f $schema,$Object.table_name,($columnNames -join ''','''),$Object.name,$clustered,$unique,$idxInclude,$descending,$where
if( -not $ForTable )
{
Push-PopOperation ('Remove-Index{0} -TableName ''{1}'' -Name ''{2}''' -f $schema,$Object.table_name,$Object.name)
Expand Down Expand Up @@ -1224,7 +1226,7 @@ from
}

Write-ExportingMessage -Schema $Object.schema_name -Type Schema
' Add-Schema -Name ''{0}'' -Owner ''{1}''{2}' -f $schema.name,$schema.owner, $description
" Add-Schema -Name '$($schema.name)'${description}"
$exportedSchemas[$schema.name] = $true
Push-PopOperation ('Remove-Schema -Name ''{0}''' -f $schema.name)
}
Expand Down
16 changes: 10 additions & 6 deletions Rivet/Functions/Get-MigrationFile.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ function Get-MigrationFile
Write-Debug -Message $Path
if( (Test-Path -Path $Path -PathType Container) )
{
Get-ChildItem -Path $Path -Filter $script:schemaFileName -ErrorAction Ignore
return Get-ChildItem -Path $Path -Filter '*_*.ps1'
}

Expand All @@ -76,10 +77,12 @@ function Get-MigrationFile
}
} |
ForEach-Object {
$isBaseline = $false
if( $_.BaseName -eq 'schema' )
{
$id = $script:schemaMigrationId # midnight on year 1, month 0, day 0.
$name = $_.BaseName
$isBaseline = $true
}
elseif( $_.BaseName -notmatch '^(\d{14})_(.+)' )
{
Expand All @@ -98,7 +101,8 @@ function Get-MigrationFile
Add-Member -MemberType NoteProperty -Name 'MigrationID' -Value $id -PassThru |
Add-Member -MemberType NoteProperty -Name 'MigrationName' -Value $name -PassThru |
Add-Member -MemberType NoteProperty -Name 'DatabaseName' -Value $DatabaseName -PassThru |
Add-Member -MemberType NoteProperty -Name 'IsRivetMigration' -Value $isRivetMigration -PassThru
Add-Member -MemberType NoteProperty -Name 'IsRivetMigration' -Value $isRivetMigration -PassThru |
Add-Member -Membertype NoteProperty -Name 'IsBaselineMigration' -Value $isBaseline -PassThru
} |
Where-Object {
if (-not ($PSBoundParameters.ContainsKey('Include')))
Expand Down Expand Up @@ -134,8 +138,8 @@ function Get-MigrationFile
foreach( $pattern in $Exclude )
{
$foundMatch = $migration.MigrationID -like $pattern -or `
$migration.MigrationName -like $pattern -or `
$migration.BaseName -like $pattern
$migration.MigrationName -like $pattern -or `
$migration.BaseName -like $pattern
if( $foundMatch )
{
return $false
Expand All @@ -150,10 +154,10 @@ function Get-MigrationFile
return $true
}

if ($_.IsRivetMigration)
if ($_.IsRivetMigration -and -not $_.IsBaselineMigration)
{
$msg = "Migration '$($_.FullName)' has an invalid ID. IDs lower than $($script:firstMigrationId) " +
'are reserved for Rivet''s internal use.'
$msg = "Migration '$($_.FullName)' has invalid ID ""$($_.MigrationID)"". IDs lower than $($script:firstMigrationId) " +
'are reserved for Rivet''s internal use.'
Write-Error $msg -ErrorAction Stop
return $false
}
Expand Down
23 changes: 9 additions & 14 deletions Rivet/Functions/Import-RivetPlugin.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,16 @@ function Import-RivetPlugin
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[AllowEmptyCollection()]
[String[]]$Path,

[Parameter(Mandatory)]
[AllowEmptyCollection()]
[String[]]$ModuleName
[Rivet_Session] $Session
)

Set-StrictMode -Version 'Latest'
Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState

Write-Timing -Message 'Import-RivetPlugin BEGIN' -Indent

$moduleNames = & {
foreach( $pluginPath in $Path )
foreach( $pluginPath in $Session.PluginPaths )
{
if( [IO.Path]::GetExtension($pluginPath) -eq '.ps1' )
{
Expand All @@ -27,13 +22,13 @@ function Import-RivetPlugin
}

Write-Timing -Message " Import BEGIN $($pluginPath)"
Import-Module -Name $pluginPath -Global -Force -PassThru |
Import-Module -Name $pluginPath -Global -Force -PassThru -Verbose:$false |
Select-Object -ExpandProperty 'Name' |
Write-Output
Write-Timing -Message " Import END $($pluginPath)"
}

$ModuleName | Write-Output
$Session.PluginModules | Write-Output
}

$commands = & {
Expand All @@ -59,9 +54,9 @@ function Import-RivetPlugin
Get-Command -CommandType Function | Where-Object { -not $_.Module }
Write-Timing -Message (' Get Functions End')
}
$script:plugins = & {
foreach( $command in $commands )

$Session.Plugins = & {
foreach( $command in $commands )
{
if( -not ($command | Get-Member -Name 'ScriptBlock') )
{
Expand All @@ -88,7 +83,7 @@ function Import-RivetPlugin
}
}

Write-Timing -Message (' Discovered {0} plugins.' -f ($plugins | Measure-Object).Count)
Write-Timing -Message (' Discovered {0} plugins.' -f ($Session.Plugins | Measure-Object).Count)

Write-Timing -Message 'Import-RivetPlugin END' -Outdent
}
15 changes: 4 additions & 11 deletions Rivet/Functions/Invoke-Rivet.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ function Invoke-Rivet
[Parameter(ParameterSetName='Redo')]
[Parameter(ParameterSetName='DropDatabase')]
[Parameter(ParameterSetName='Checkpoint')]
[Parameter(ParameterSetName='InitializeSchema')]
[String[]] $Database,

# The environment you're working in. Controls which settings Rivet loads from the `rivet.json` configuration file.
Expand All @@ -69,7 +68,6 @@ function Invoke-Rivet
[Parameter(ParameterSetName='Redo')]
[Parameter(ParameterSetName='DropDatabase')]
[Parameter(ParameterSetName='Checkpoint')]
[Parameter(ParameterSetName='InitializeSchema')]
[String] $Environment,

# The path to the Rivet configuration file. Default behavior is to look in the current directory for a
Expand All @@ -83,21 +81,16 @@ function Invoke-Rivet
[Parameter(ParameterSetName='Redo')]
[Parameter(ParameterSetName='DropDatabase')]
[Parameter(ParameterSetName='Checkpoint')]
[Parameter(ParameterSetName='InitializeSchema')]
[String] $ConfigFilePath,

# Drops the database(s) for the current environment when given. User will be prompted for confirmation when
# used.
[Parameter(ParameterSetName='DropDatabase')]
[Parameter(Mandatory, ParameterSetName='DropDatabase')]
[switch] $DropDatabase,

# Checkpoints the current state of the database so that it can be re-created.
[Parameter(ParameterSetName='Checkpoint')]
[switch] $Checkpoint,

# Initializes the database, including baseline schema. Use the -Checkpoint switch to create a database baseline.
[Parameter(ParameterSetName='InitializeSchema')]
[switch] $InitializeSchema
[Parameter(Mandatory, ParameterSetName='Checkpoint')]
[switch] $Checkpoint
)

Set-StrictMode -Version 'Latest'
Expand Down Expand Up @@ -160,7 +153,7 @@ Found no databases to migrate. This can be a few things:
{
foreach( $databaseItem in $databaseList )
{
$query = "drop database $($databaseItem.Name)"
$query = "drop database [$($databaseItem.Name)]"
Invoke-Query -Session $session -Query $query
}
}
Expand Down
Loading

0 comments on commit a01fbb8

Please sign in to comment.