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); process.stdout.write(JSON.stringify({ client: clientName, rowCount: Array.isArray(rows) ? rows.length : 0, rows, })); } 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 try { $json = & node $tempNodeFile $projectRoot $configResolved.Path $DbClient $Query if ($LASTEXITCODE -ne 0) { throw "Node query runner exited with code $LASTEXITCODE." } } finally { Remove-Item -Path $tempNodeFile -ErrorAction SilentlyContinue } $result = $json | ConvertFrom-Json Write-Host "Client: $($result.client)" 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 }