WMS_MAIN/script/db-query.ps1

123 lines
3.5 KiB
PowerShell

param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$Query,
[Parameter(Mandatory = $false)]
[string]$DbClient = "wms",
[Parameter(Mandatory = $false)]
[string]$ConfigPath = ".\\config\\config.local.js",
[switch]$AsTable
)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$scriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$projectRoot = Split-Path -Parent $scriptRoot
$configFullPath = Join-Path $projectRoot $ConfigPath
$configResolved = Resolve-Path -Path $configFullPath -ErrorAction Stop
$nodeScript = @'
const path = require("path");
const { createRequire } = require("module");
(async () => {
const projectRoot = process.argv[2];
const configPath = process.argv[3];
const clientName = process.argv[4];
const query = process.argv[5];
const projectRequire = createRequire(path.join(projectRoot, "package.json"));
const mysql = projectRequire("mysql2/promise");
if (!query) {
throw new Error("Query is required.");
}
const configFactory = require(path.resolve(configPath));
const config = typeof configFactory === "function"
? configFactory({ name: "wms-debug" })
: configFactory;
const client = config
&& config.mysql
&& config.mysql.clients
&& config.mysql.clients[clientName];
if (!client) {
throw new Error(`MySQL client "${clientName}" not found in config.mysql.clients.`);
}
const connection = await mysql.createConnection({
host: client.host,
port: Number(client.port),
user: client.user,
password: client.password,
database: client.database,
charset: client.charset || "utf8mb4",
});
try {
const [rows] = await connection.query(query);
const payload = JSON.stringify({
client: clientName,
host: client.host,
port: client.port,
database: client.database,
rowCount: Array.isArray(rows) ? rows.length : 0,
rows,
});
const outPath = process.argv[6];
if (outPath) {
require('fs').writeFileSync(outPath, payload, 'utf8');
} else {
process.stdout.write(payload);
}
} finally {
await connection.end();
}
})().catch((err) => {
process.stderr.write(err && err.stack ? err.stack : String(err));
process.exit(1);
});
'@
$tempFile = New-TemporaryFile
$tempNodeFile = [System.IO.Path]::ChangeExtension($tempFile.FullName, ".cjs")
Move-Item -Path $tempFile.FullName -Destination $tempNodeFile -Force
Set-Content -Path $tempNodeFile -Value $nodeScript -Encoding UTF8
$jsonOutFile = [System.IO.Path]::ChangeExtension(
([System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), 'db-query-' + [Guid]::NewGuid().ToString())),
'.json'
)
try {
$null = & node $tempNodeFile $projectRoot $configResolved.Path $DbClient $Query $jsonOutFile
if ($LASTEXITCODE -ne 0) {
throw "Node query runner exited with code $LASTEXITCODE."
}
} finally {
Remove-Item -Path $tempNodeFile -ErrorAction SilentlyContinue
}
try {
$result = Get-Content -LiteralPath $jsonOutFile -Raw -Encoding utf8 | ConvertFrom-Json
} finally {
Remove-Item -Path $jsonOutFile -ErrorAction SilentlyContinue
}
Write-Host "Client: $($result.client)"
Write-Host "Target: $($result.host):$($result.port)/$($result.database)"
Write-Host "Rows: $($result.rowCount)"
if ($AsTable) {
if (($result.rows -is [System.Array]) -and $result.rows.Count -gt 0) {
$result.rows | Format-Table -AutoSize
} else {
Write-Host "No tabular rows to render."
}
} else {
$result | ConvertTo-Json -Depth 50
}