76 lines
2.3 KiB
PowerShell
76 lines
2.3 KiB
PowerShell
param(
|
|
[Parameter(Mandatory = $true)]
|
|
[string]$SqlFile
|
|
)
|
|
|
|
$ErrorActionPreference = 'Stop'
|
|
|
|
$root = Split-Path -Parent $PSScriptRoot
|
|
$configPath = Join-Path $root 'ruoyi-admin\src\main\resources\application-druid.yml'
|
|
$sqlPath = if ([System.IO.Path]::IsPathRooted($SqlFile)) { $SqlFile } else { Join-Path $root $SqlFile }
|
|
|
|
if (-not (Test-Path $configPath)) {
|
|
throw "application-druid.yml not found"
|
|
}
|
|
if (-not (Test-Path $sqlPath)) {
|
|
throw "SQL file not found: $SqlFile"
|
|
}
|
|
|
|
$master = @{}
|
|
$inMaster = $false
|
|
foreach ($line in [System.IO.File]::ReadLines($configPath)) {
|
|
if ($line -match '^\s*master:\s*$') {
|
|
$inMaster = $true
|
|
continue
|
|
}
|
|
if ($inMaster -and $line -match '^\s*slave:\s*$') {
|
|
break
|
|
}
|
|
if ($inMaster -and $line -match '^\s*(url|username|password):\s*(.*)\s*$') {
|
|
$master[$matches[1]] = $matches[2]
|
|
}
|
|
}
|
|
|
|
if (-not $master.url -or -not $master.username -or -not $master.password) {
|
|
throw 'Missing master datasource settings'
|
|
}
|
|
|
|
$urlMatch = [regex]::Match($master.url, '^jdbc:sqlserver://(?<server>[^;]+);(?<params>.*)$')
|
|
if (-not $urlMatch.Success) {
|
|
throw 'Unsupported SQL Server JDBC URL'
|
|
}
|
|
|
|
$server = $urlMatch.Groups['server'].Value -replace ':(\d+)$', ',$1'
|
|
$params = $urlMatch.Groups['params'].Value
|
|
$dbMatch = [regex]::Match($params, '(?i)(^|;)databaseName=(?<db>[^;]+)')
|
|
if (-not $dbMatch.Success) {
|
|
throw 'databaseName missing in JDBC URL'
|
|
}
|
|
|
|
$database = $dbMatch.Groups['db'].Value
|
|
$connectionString = "Server=$server;Database=$database;User ID=$($master.username);Password=$($master.password);Encrypt=False;TrustServerCertificate=True;"
|
|
|
|
Add-Type -AssemblyName System.Data
|
|
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
|
|
|
|
try {
|
|
$sql = [System.IO.File]::ReadAllText($sqlPath)
|
|
$batches = [regex]::Split($sql, '(?im)^\s*GO\s*$')
|
|
$connection.Open()
|
|
foreach ($batch in $batches) {
|
|
if ([string]::IsNullOrWhiteSpace($batch)) {
|
|
continue
|
|
}
|
|
$command = $connection.CreateCommand()
|
|
$command.CommandTimeout = 120
|
|
$command.CommandText = $batch
|
|
[void]$command.ExecuteNonQuery()
|
|
}
|
|
Write-Output "Applied SQL file to $database"
|
|
}
|
|
finally {
|
|
if ($connection.State -ne [System.Data.ConnectionState]::Closed) {
|
|
$connection.Close()
|
|
}
|
|
}
|