Public/InstallHelpers/Install.Database.Functions.psm1

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop";
#Requires -Version 5.0


function _loadDbaTools() {
    [string] $originalLocation = (Get-Location).Path
    Set-Location $PSScriptRoot 
    $scriptRootParent = (Get-Item .).Parent.FullName
    Import-Module "$scriptRootParent\ModuleHelpers\Module.Functions.psm1"
    LoadModule -moduleNameOrPath 'dbatools' -installViaNuGet $true
    return $originalLocation
}


# NOTE: This function depends on the dbatools module
# TODO: Ensure dbatools is installed/loaded prior in this function
function DropDatabase(
    [Parameter(mandatory=$true)]
    [System.Management.Automation.PSCredential] $credential,
    
    [Parameter(mandatory=$true)]
    [string] $dbHost,

    [Parameter(mandatory=$true)]
    [string] $dbName
) {
    # TODO: Can I Parameterize this? (I don't think so...)
    [string] $dropDbSql = @"
USE [master]
GO
IF DB_ID('$dbName') IS NOT NULL
BEGIN
    DROP DATABASE [$dbName]
END
"@


    # DOCS: https://docs.dbatools.io/#Invoke-DbaQuery
    $result = Invoke-DbaQuery `
        -SqlInstance $dbHost `
        -Query $dropDbSql `
        -SqlCredential $credential        
    Write-Host $result
    # TODO: Handle errors with exit 1
}


# EX ARGS FOR PARAMS: -Query 'SELECT * FROM users WHERE Givenname = @name' -SqlParameters @{ Name = "Maria" }
function RunSql(
    [Parameter(mandatory=$true)]
    [System.Collections.Hashtable] $dbaQueryParams = @{ 
        SqlInstance = $Env:ComputerName
        Query = 'SELECT 1'
    }    
) {
    [string] $originalLocation = _loadDbaTools

    # DOCS: https://docs.dbatools.io/#Invoke-DbaQuery
    # NOTE: We're using splatting below (https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting?view=powershell-5.1)
    $result = Invoke-DbaQuery @dbaQueryParams
        
    return $result
    # TODO: Handle errors with exit 1

    # INTENT: Avoid interfering with work directories in consuming scripts
    Set-Location $originalLocation
}

Export-ModuleMember -Function "*"