فینورا پرو - سامانه جامع حسابداری و صدور فاکتور

feat/a02-opt-in-isolated-sql-restore-executor-20261030
a02/strict-export-preflight-20261018 audit/a01-readonly-invoice-metadata-20261101 ci/a06-require-trusted-issuer-for-release ci/main-postmerge-phase-a-validation-20261020 ci/phase-a-controlled-public-release design/issue-5-commercial-corrections-adr docs/a01-a02-a05-oct23-verified-evidence docs/a01-cheque-endorsement-evidence-20261022 docs/a01-cheque-event-date-evidence-20261021 docs/a01-explicit-refund-reason-evidence-20261021 docs/a01-refund-auth-status-20261020 docs/a01-refund-trace-evidence-20261020 docs/a02-102-evidence-20261018 docs/a02-pr104-evidence-20261018 docs/a02-pr106-evidence-20261019 docs/a02-pr108-ten-tests-20261019 docs/a02-private-sql-backup-evidence-20261111 docs/a03-merge-status-sync-20261020 docs/a04-software-gate-acceptance-20261020 docs/feature-matrix-20261014 docs/finora-master-execution-playbook docs/four-phase-execution-20261014 docs/four-phase-roadmap-20261014 docs/holoo-lab-stabilization-phase1-20261111 docs/holoo-runtime-schema-audit-20261111 docs/ops-142-governance-5-1-3-20261030 docs/phase-a-a01-a02-a06-a08-verified-evidence-20261023 docs/phase-a-a01-a05-a06-evidence-20261023 docs/phase-a-independent-acceptance-evidence docs/phase-a-pr110-evidence-20261019 docs/project-status-phase-a-20261014 feat/a01-referenced-return-corrections feat/a01-referenced-returns-on-main feat/a02-atomic-opening-ledger-preflight feat/a02-holoo-compatibility-preflight feat/a02-holoo-declared-control-totals feat/a02-holoo-explicit-csv-gate feat/a02-holoo-safe-zip-intake-offline-webview2-20261030 feat/a02-offline-sql-server-provisioning-20261030 feat/a02-opening-balance-dry-run feat/a02-opening-ledger-admin-ui feat/a02-opt-in-isolated-sql-restore-executor-20261030 feat/a02-private-holoo-zip-staging-20261030 feat/a02-safe-isolated-restore-plan-20261030 feat/a02-sql-backup-header-verifyonly-20261030 feat/a03-audit-schema-atomic-events feat/a03-complete-manual-journal-audit feat/a05-cheque-treasury-reconciliation feat/a06-signed-offline-license-activation feat/a08-synthetic-performance-baseline feat/phase-a-accounting-benchmark-return-preview feat/phase-a-ledger-settlement-diagnostics feature/v2-reconciliation-20261013 fix/a01-atomic-confirm-ui-one-shot-20261031 fix/a01-cheque-clearance-explicit-account-20261023 fix/a01-cheque-contractual-due-date-validity-20261023 fix/a01-cheque-endorsement-counterparty-20261022 fix/a01-cheque-event-date-open-period-20261021 fix/a01-cumulative-return-amount-cap fix/a01-explicit-refund-reason-approval-20261021 fix/a01-manager-authorized-customer-refunds-20261020 fix/a01-no-implicit-refund fix/a01-one-shot-confirm-on-atomic-import-20261031 fix/a01-refund-and-overcollection-net-cash fix/a01-refund-correction-trace-20261020 fix/a02-atomic-excel-master-merge-20261031 fix/a02-canonical-mapping-contract-20261018 fix/a02-disable-destructive-excel-replace-20261031 fix/a02-holoo-invoice-line-coverage-20261023 fix/a02-holoo-preflight-required-invoice-lines-20261023 fix/a02-mapping-contract-20261018 fix/a02-opening-preflight-unbalanced-report fix/a02-orphan-mapping-20261018 fix/a02-private-excel-import-session-20261031 fix/a02-strict-export-input-20261019 fix/a03-append-only-full-backup-import fix/a03-append-only-write-guard fix/a03-block-transaction-clear-append-only-20261016 fix/a03-chain-validation-20261020 fix/a03-company-scoped-audit-data-access fix/a03-deny-direct-audit-write-20261019 fix/a03-escaped-expense-list-20261031 fix/a03-escaped-financial-record-ids-20261031 fix/a03-financial-ledger-actions-and-print-20261031 fix/a04-backup-checksum-preflight fix/a04-company-audit-replay-stable-compare fix/a04-company-backup-source-isolation-20261020 fix/a04-full-restore-posted-financial-integrity fix/a04-reject-mixed-company-backup-20261019 fix/a04-replace-immutable-posted-ledger fix/a04-restore-financial-journal-references fix/a04-service-source-company-boundary-20261020 fix/a05-block-inactive-treasury-settlements fix/a05-cheque-cash-evidence-reconciliation-20261023 fix/a05-cheque-ledger-and-bank-reconciliation-20261023 fix/a05-fiscal-close-invariant-gates fix/a06-backup-restore-user-privileges fix/a06-license-user-company-quota-20261023 fix/a06-malformed-trial-state-fail-closed fix/a06-offline-clock-fail-closed-20261019 fix/a07-indexeddb-blocked-startup fix/a07-offline-bundled-assets fix/a07-version-and-startup-banner fix/issue-7-company-backup-isolation fix/p0-deterministic-fractional-invoice-money-20261031 fix/p0-fractional-quantity-input-20261031 fix/p0-fractional-quantity-integrated-20261031 fix/p0-invoice-posting-invariants-20261031 fix/p0-legacy-stock-and-product-inputs-20261031 fix/p0-reports-immutable-cogs-20261101 fix/p0-verified-financial-percent-20261031 fix/p0-zero-discount-report-revenue-20261101 fix/phase-a-backup-app-version fix/phase-a-backup-integrity-checksum fix/phase-a-backup-record-id-validation-20261014 fix/phase-a-backup-version-validation-20261014 fix/phase-a-closure-pack3-20261101 fix/phase-a-entitlement-payload-validation fix/phase-a-gate-exact-evidence-20261019 fix/phase-a-pack4-stock-scope-20261101 fix/phase-a-pack5-integrated-evidence-20261101 fix/phase-a-pack6-atomic-legacy-20261101 fix/phase-a-restore-envelope-and-rollback fix/phase-a-settings-admin-gate fix/print-browser-header-footer-20261014 fix/q01-expense-security-probe-exact-option-20261031 fix/q01-financial-grid-labels-20261031 fix/q01-form-label-association-20261031 fix/q01-native-evidence-integrity-20261030 fix/q01-number-input-persian-decimal-20261031 fix/q01-responsive-dashboard-and-cheque-table-20261031 fix/q01-safe-ui-action-audit-coverage-20261031 fix/q01-visible-desktop-sidebar-and-safe-confirm-20261030 fix/roadmap-metadata-sync-20261014 gate/a03-audit-metadata-validation-20261019 integration/a02-windows-holoo-setup-candidate-20261030 license-server main perf/a07-lazy-load-excel perf/a08-cheque-reconciliation-account-index-20261023 perf/a08-paginated-reports-20261101 phase1-restore-hardening planning/holoo-execution-20261013 planning/roadmap-project-management-20261014 qa/native-click-coverage-audit-20261030 release/v2.0.0 test/a01-native-endorsement-mandatory-20261023 test/a01-native-purchase-return-guardrails test/a01-native-sale-return-financial-guardrails test/a01-safe-integer-boundary-20261019 test/a02-native-opening-dry-run-rejections test/a02-native-positive-opening-ledger test/a04-native-corrupt-fbackup-20261016 test/a04-native-encrypted-company-backup test/a04-native-encrypted-company-backup-main test/a04-native-late-transaction-rollback test/a04-native-windows-backup-recovery test/a04-real-edge-v6-v7-migration test/a04-real-native-interrupted-restore test/a05-native-draft-ledger-and-repeat-close-20261016 test/a05-native-fiscal-close-guardrails test/a07-native-multipage-print-engine test/a07-native-origin-provenance test/a07-native-webview2-offline-routes test/a07-windows-offline-startup-smoke test/a08-installed-webview2-60k-baseline test/a08-native-webview2-heap-metrics test/a08-windows-synthetic-performance-baseline test/github-write-access-20261009 test/native-win-ui-routes-after-finance-backup test/phase-a-combined-a01-a05-a08-final-evidence test/phase-a-combined-native-acceptance-matrix test/phase-a-ledger-invariants-20261014 test/phase-a-native-all-routes-on-merged-lab test/phase-a-native-encrypted-backup test/phase-a-native-finance-backup-matrix test/phase-a-native-ui-and-backup-smoke test/phase-a-windows-native-installer-lab work/a08-dispatch-activation-20261123 work/a08-memory-stability-20261123 work/finance-curated-20261123
ps1 374 lines 14.9 KB
Raw
1 #requires -Version 5.1
2 <#
3 A02: owner-approved, LOCAL-only, isolated SQL Server RESTORE. Not the public wizard.
4 No SQL install, data mapping/import, remote instance access, WITH REPLACE or DROP.
5 Use only on a dedicated disposable SQL instance named FINORAMIG.
6 No owner backup is ever used by public GitHub CI; -Mode Test uses synthetic rows.
7 #>
8 [CmdletBinding()]
9 param(
10 [ValidateSet('Test', 'Inspect', 'Restore')]
11 [string]$Mode = 'Test',
12 [string]$BackupPath = '',
13 [ValidatePattern('^FINORAMIG$')]
14 [string]$InstanceName = 'FINORAMIG',
15 [string]$ConsentPhrase = ''
16 )
17 Set-StrictMode -Version Latest
18 $ErrorActionPreference = 'Stop'
19
20 function Sql-Literal([string]$Value) {
21 if ([string]::IsNullOrWhiteSpace($Value) -or $Value.IndexOf([char]0) -ge 0) {
22 throw 'A02_INVALID_SQL_LITERAL'
23 }
24 return "N'" + $Value.Replace("'", "''") + "'"
25 }
26
27 function Assert-LocalPathShape([string]$Value) {
28 if ([string]::IsNullOrWhiteSpace($Value) -or
29 $Value -notmatch '^[A-Za-z]:\\' -or
30 $Value -match '[/\x00-\x1f<>"|?*]' -or
31 $Value.Substring(2).Contains(':')) {
32 throw 'A02_UNSAFE_LOCAL_PATH'
33 }
34 foreach ($segment in $Value.Substring(3).Split('\')) {
35 if ([string]::IsNullOrWhiteSpace($segment) -or
36 $segment -eq '.' -or $segment -eq '..' -or
37 $segment.EndsWith(' ') -or $segment.EndsWith('.')) {
38 throw 'A02_AMBIGUOUS_PATH'
39 }
40 }
41 return $Value
42 }
43
44 function Assert-LocalFilesystemSource([string]$Value) {
45 $path = Assert-LocalPathShape $Value
46 $drive = [System.IO.DriveInfo]::new($path.Substring(0, 1))
47 if ($drive.DriveType -ne [System.IO.DriveType]::Fixed -and
48 $drive.DriveType -ne [System.IO.DriveType]::Removable) {
49 throw 'A02_SOURCE_NOT_LOCAL_DISK'
50 }
51 $file = New-Object System.IO.FileInfo($path)
52 if (-not $file.Exists -or $file.Length -le 0 -or $file.Length -gt 4GB) {
53 throw 'A02_SOURCE_FILE_OR_SIZE_INVALID'
54 }
55 if (($file.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) {
56 throw 'A02_SOURCE_LINK_DISALLOWED'
57 }
58 $parent = $file.Directory
59 while ($null -ne $parent) {
60 if (($parent.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) {
61 throw 'A02_SOURCE_PARENT_LINK_DISALLOWED'
62 }
63 $parent = $parent.Parent
64 }
65 return $file.FullName
66 }
67
68 function New-RandomDatabaseName {
69 $rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
70 try {
71 [byte[]]$bytes = New-Object byte[] 16
72 $rng.GetBytes($bytes)
73 return 'FinoraHoloo_' + [BitConverter]::ToString($bytes).Replace('-', '').ToLowerInvariant()
74 } finally { $rng.Dispose() }
75 }
76
77 function New-LocalRestorePlan(
78 [string]$BackupFile, [string]$DataDirectory, [string]$LogDirectory,
79 [string]$DatabaseName, [object[]]$Files
80 ) {
81 $null = Assert-LocalPathShape $BackupFile
82 $null = Assert-LocalPathShape $DataDirectory
83 $null = Assert-LocalPathShape $LogDirectory
84 if ($DatabaseName -cnotmatch '^FinoraHoloo_[0-9a-f]{32}$') {
85 throw 'A02_INVALID_DATABASE_NAME'
86 }
87 if ($null -eq $Files -or $Files.Count -lt 2 -or $Files.Count -gt 16) {
88 throw 'A02_FILELIST_COUNT_UNSUPPORTED'
89 }
90 $seen = [System.Collections.Generic.HashSet[string]]::new(
91 [System.StringComparer]::OrdinalIgnoreCase
92 )
93 $moves = @()
94 $data = 0
95 $logs = 0
96 $totalBytes = [long]0
97 foreach ($file in $Files) {
98 $logical = [string]$file.LogicalName
99 $type = [string]$file.Type
100 [long]$size = $file.Size
101 if ([string]::IsNullOrWhiteSpace($logical) -or $logical.Length -gt 128 -or
102 $logical -match '[\x00-\x1f]' -or
103 -not $seen.Add($logical) -or
104 $size -le 0 -or $size -gt 2TB) {
105 throw 'A02_FILELIST_UNSAFE_ENTRY'
106 }
107 if ($type -eq 'D') {
108 $data++
109 $ext = if ($data -eq 1) { '.mdf' } else { '.ndf' }
110 $directory = $DataDirectory
111 } elseif ($type -eq 'L') {
112 $logs++
113 $ext = '.ldf'
114 $directory = $LogDirectory
115 } else { throw 'A02_UNSUPPORTED_SQL_FILE_TYPE' }
116 if ($totalBytes -gt [long]::MaxValue - $size) {
117 throw 'A02_FILELIST_SIZE_OVERFLOW'
118 }
119 $totalBytes += $size
120 $filename = $DatabaseName + '_file' + ($moves.Count + 1).ToString('00') + $ext
121 $target = [System.IO.Path]::Combine($directory, $filename)
122 $null = Assert-LocalPathShape $target
123 $moves += [pscustomobject]@{
124 Logical = $logical; Target = $target; Type = $type; Bytes = $size
125 }
126 }
127 if ($data -eq 0 -or $logs -eq 0) {
128 throw 'A02_DATA_AND_LOG_FILES_REQUIRED'
129 }
130 $clauses = @($moves | ForEach-Object {
131 'MOVE ' + (Sql-Literal $_.Logical) + ' TO ' + (Sql-Literal $_.Target)
132 })
133 $sourceSql = 'FROM DISK = ' + (Sql-Literal $BackupFile) +
134 ' WITH FILE = 1, ' + ($clauses -join ', ')
135 $guard = 'IF DB_ID(' + (Sql-Literal $DatabaseName) +
136 ") IS NOT NULL THROW 51001, 'A02_DATABASE_COLLISION', 1;"
137 $verify = 'RESTORE VERIFYONLY ' + $sourceSql + ';'
138 $restore = $guard + [Environment]::NewLine +
139 'RESTORE DATABASE [' + $DatabaseName + '] ' +
140 $sourceSql + ', RECOVERY, STATS = 10;'
141 return [pscustomobject]@{
142 DatabaseName = $DatabaseName
143 Moves = @($moves)
144 TotalBytes = $totalBytes
145 VerifySql = $verify
146 RestoreSql = $restore
147 RestoreExecuted = $false
148 CanImport = $false
149 }
150 }
151
152 function Invoke-SqlRows($Connection, [string]$Sql) {
153 $cmd = $Connection.CreateCommand()
154 $cmd.CommandText = $Sql
155 $cmd.CommandTimeout = 300
156 $adapter = New-Object System.Data.SqlClient.SqlDataAdapter($cmd)
157 $rows = New-Object System.Data.DataTable
158 try {
159 [void]$adapter.Fill($rows)
160 return ,$rows
161 } finally {
162 $adapter.Dispose()
163 $cmd.Dispose()
164 }
165 }
166
167 function Invoke-SqlCommand($Connection, [string]$Sql, [int]$Timeout = 1800) {
168 $cmd = $Connection.CreateCommand()
169 $cmd.CommandText = $Sql
170 $cmd.CommandTimeout = $Timeout
171 try { [void]$cmd.ExecuteNonQuery() }
172 finally { $cmd.Dispose() }
173 }
174
175 function Assert-PlanCollisionFree($Connection, $Plan) {
176 # Only read system catalogs; no CREATE/DROP/ALTER.
177 $catalog = Invoke-SqlRows $Connection 'SELECT physical_name FROM sys.master_files'
178 $names = Invoke-SqlRows $Connection 'SELECT name FROM sys.databases'
179 try {
180 foreach ($r in $names.Rows) {
181 if ([string]::Equals([string]$r['name'], $Plan.DatabaseName,
182 [System.StringComparison]::OrdinalIgnoreCase)) {
183 throw 'A02_DATABASE_COLLISION'
184 }
185 }
186 foreach ($move in $Plan.Moves) {
187 if ([System.IO.File]::Exists($move.Target) -or
188 [System.IO.Directory]::Exists($move.Target)) {
189 throw 'A02_DESTINATION_FILE_COLLISION'
190 }
191 foreach ($row in $catalog.Rows) {
192 if ([string]::Equals([string]$row['physical_name'], $move.Target,
193 [System.StringComparison]::OrdinalIgnoreCase)) {
194 throw 'A02_EXISTING_SQL_FILE_COLLISION'
195 }
196 }
197 }
198 } finally {
199 $catalog.Dispose()
200 $names.Dispose()
201 }
202 }
203
204 function Assert-DestinationDiskSpace($Plan) {
205 # Require at least 2 GiB reserve beyond the logical file sizes per drive.
206 $required = @{}
207 foreach ($move in $Plan.Moves) {
208 $drive = $move.Target.Substring(0, 1).ToUpperInvariant()
209 if (-not $required.ContainsKey($drive)) { $required[$drive] = [long]0 }
210 $required[$drive] += [long]$move.Bytes
211 }
212 foreach ($drive in $required.Keys) {
213 $info = [System.IO.DriveInfo]::new($drive)
214 if ($info.DriveType -ne [System.IO.DriveType]::Fixed -or
215 -not $info.IsReady -or
216 $info.AvailableFreeSpace -lt ($required[$drive] + 2GB)) {
217 throw 'A02_DESTINATION_DISK_INSUFFICIENT'
218 }
219 }
220 }
221
222 function Invoke-SelfTest {
223 $name = 'FinoraHoloo_0123456789abcdef0123456789abcdef'
224 $files = @(
225 [pscustomobject]@{ LogicalName = "Data';DROP DATABASE master;--"; Type = 'D'; Size = 1024 },
226 [pscustomobject]@{ LogicalName = 'Log'; Type = 'L'; Size = 2048 }
227 )
228 $p = New-LocalRestorePlan "D:\Private\O'Connor.bak" 'C:\SqlData' 'C:\SqlLog' $name $files
229 if (-not $p.VerifySql.Contains("O''Connor.bak") -or
230 -not $p.RestoreSql.Contains("Data'';DROP DATABASE master;--") -or
231 $p.RestoreSql -match '(?i)\bWITH\s+REPLACE\b' -or
232 ($p.RestoreSql.Split([string[]]@('RESTORE DATABASE'), [System.StringSplitOptions]::None)).Count -ne 2 -or
233 $p.Moves.Count -ne 2) { throw 'A02_SELFTEST_SQL_PLAN' }
234 foreach ($bad in @('relative\file.bak', '\\server\share\a.bak',
235 'C:\Private\..\file.bak', 'C:\Private\file.bak:ads', 'C:/Private/file.bak')) {
236 $rejected = $false
237 try { $null = Assert-LocalPathShape $bad }
238 catch { $rejected = $true }
239 if (-not $rejected) { throw 'A02_SELFTEST_UNSAFE_PATH' }
240 }
241 $badType = @(
242 [pscustomobject]@{ LogicalName = 'Data'; Type = 'D'; Size = 1024 },
243 [pscustomobject]@{ LogicalName = 'Fs'; Type = 'S'; Size = 1024 }
244 )
245 $rejected = $false
246 try { $null = New-LocalRestorePlan 'D:\copy.bak' 'C:\Data' 'C:\Log' $name $badType }
247 catch { $rejected = $true }
248 if (-not $rejected) { throw 'A02_SELFTEST_FILE_TYPE' }
249 [pscustomobject]@{
250 status = 'selftest-passed'; sqlConnectionOpened = $false
251 backupOpened = $false; databaseModified = $false; canImport = $false
252 } | ConvertTo-Json -Compress
253 }
254
255 if ($Mode -eq 'Test') {
256 Invoke-SelfTest
257 return
258 }
259
260 # A02: explicit consent required before potentially creating a new database.
261 if ($Mode -eq 'Restore' -and
262 $ConsentPhrase -cne 'I_AUTHORIZE_A_NEW_ISOLATED_SQL_DATABASE') {
263 Write-Error 'A02_EXPLICIT_OWNER_CONSENT_REQUIRED'
264 exit 2
265 }
266 $connection = $null
267 try {
268 $localBackup = Assert-LocalFilesystemSource $BackupPath
269 # Bind metadata/VERIFYONLY and eventual restore to unchanged file bytes.
270 # Never output this private source fingerprint to console or CI.
271 $sourceHash = (Get-FileHash -LiteralPath $localBackup -Algorithm SHA256).Hash
272 $builder = New-Object System.Data.SqlClient.SqlConnectionStringBuilder
273 $builder.DataSource = 'lpc:.\FINORAMIG'
274 $builder.InitialCatalog = 'master'
275 $builder.IntegratedSecurity = $true
276 $builder.Encrypt = $true
277 $builder.TrustServerCertificate = $true
278 $builder.ConnectTimeout = 10
279 $builder.Pooling = $false
280 $connection = New-Object System.Data.SqlClient.SqlConnection($builder.ToString())
281 $connection.Open()
282 $version = Invoke-SqlRows $connection @"
283 SELECT TRY_CAST(SERVERPROPERTY('ProductMajorVersion') AS int) AS Major,
284 CAST(SERVERPROPERTY('InstanceName') AS nvarchar(128)) AS InstanceName,
285 CAST(SERVERPROPERTY('InstanceDefaultDataPath') AS nvarchar(4000)) AS DataDir,
286 CAST(SERVERPROPERTY('InstanceDefaultLogPath') AS nvarchar(4000)) AS LogDir;
287 "@
288 if ($version.Rows.Count -ne 1 -or
289 [string]$version.Rows[0]['InstanceName'] -ine 'FINORAMIG') {
290 throw 'A02_SQL_INSTANCE_NOT_DEDICATED'
291 }
292 [int]$serverMajor = $version.Rows[0]['Major']
293 if ($serverMajor -lt 11) { throw 'A02_SQL_INSTANCE_TOO_OLD' }
294 $dataPath = [string]$version.Rows[0]['DataDir']
295 $logPath = [string]$version.Rows[0]['LogDir']
296 if ($dataPath.EndsWith('\')) { $dataPath = $dataPath.TrimEnd('\') }
297 if ($logPath.EndsWith('\')) { $logPath = $logPath.TrimEnd('\') }
298 $null = Assert-LocalPathShape $dataPath
299 $null = Assert-LocalPathShape $logPath
300 foreach ($folder in @($dataPath, $logPath)) {
301 if (-not [System.IO.Directory]::Exists($folder)) {
302 throw 'A02_SQL_DEFAULT_DIRECTORY_MISSING'
303 }
304 }
305 $sourceLiteral = Sql-Literal $localBackup
306 $header = Invoke-SqlRows $connection ('RESTORE HEADERONLY FROM DISK = ' + $sourceLiteral)
307 if ($header.Rows.Count -ne 1 -or
308 [int]$header.Rows[0]['BackupType'] -ne 1 -or
309 [int]$header.Rows[0]['Position'] -ne 1) {
310 throw 'A02_NOT_SINGLE_STANDALONE_FULL_BACKUP'
311 }
312 if ($header.Columns.Contains('IsDamaged') -and
313 $header.Rows[0]['IsDamaged'] -ne [DBNull]::Value -and
314 [bool]$header.Rows[0]['IsDamaged']) {
315 throw 'A02_SOURCE_HEADER_DAMAGED'
316 }
317 [int]$sourceMajor = $header.Rows[0]['SoftwareVersionMajor']
318 if ($sourceMajor -lt 9 -or $sourceMajor -gt $serverMajor) {
319 throw 'A02_SOURCE_SQL_VERSION_INCOMPATIBLE'
320 }
321 $files = Invoke-SqlRows $connection ('RESTORE FILELISTONLY FROM DISK = ' + $sourceLiteral)
322 $plan = New-LocalRestorePlan $localBackup $dataPath $logPath (
323 New-RandomDatabaseName
324 ) @($files.Rows)
325 Assert-DestinationDiskSpace $plan
326 Assert-PlanCollisionFree $connection $plan
327 Invoke-SqlCommand $connection $plan.VerifySql 1800
328 if ((Get-FileHash -LiteralPath $localBackup -Algorithm SHA256).Hash -cne $sourceHash) {
329 throw 'A02_SOURCE_BACKUP_CHANGED_AFTER_VERIFY'
330 }
331 if ($Mode -eq 'Inspect') {
332 [pscustomobject]@{
333 status = 'backup-verifyonly-passed'
334 sourceSqlMajor = $sourceMajor; engineSqlMajor = $serverMajor
335 fileCount = $plan.Moves.Count; canImport = $false
336 restoreExecuted = $false; financialReconciled = $false
337 } | ConvertTo-Json -Compress
338 return
339 }
340 # Recheck to narrow races; SQL itself also refuses existing database
341 # without WITH REPLACE. This cannot prove true exclusive use of instance.
342 Assert-PlanCollisionFree $connection $plan
343 if ((Get-FileHash -LiteralPath $localBackup -Algorithm SHA256).Hash -cne $sourceHash) {
344 throw 'A02_SOURCE_BACKUP_CHANGED_BEFORE_RESTORE'
345 }
346 Invoke-SqlCommand $connection $plan.RestoreSql 3600
347 $online = Invoke-SqlRows $connection (
348 'SELECT state_desc FROM sys.databases WHERE name = ' +
349 (Sql-Literal $plan.DatabaseName)
350 )
351 if ($online.Rows.Count -ne 1 -or [string]$online.Rows[0]['state_desc'] -ne 'ONLINE') {
352 throw 'A02_ISOLATED_DATABASE_NOT_ONLINE'
353 }
354 $schema = Invoke-SqlRows $connection (
355 'SELECT (SELECT COUNT(*) FROM [' + $plan.DatabaseName +
356 '].sys.tables) AS TableCount, (SELECT COUNT(*) FROM [' +
357 $plan.DatabaseName + '].sys.columns) AS ColumnCount'
358 )
359 [pscustomobject]@{
360 status = 'isolated-restore-completed-needs-mapping-and-reconciliation'
361 databaseName = $plan.DatabaseName
362 tableCount = [int]$schema.Rows[0]['TableCount']
363 columnCount = [int]$schema.Rows[0]['ColumnCount']
364 canImport = $false; financialReconciled = $false
365 importPerformed = $false
366 } | ConvertTo-Json -Compress
367 } catch {
368 # Do not leak source paths, company names, SQL logical names, credentials,
369 # raw SQL errors or source financial data into logs/public CI.
370 Write-Error 'A02_SQL_ISOLATED_RESTORE_OR_PREFLIGHT_FAILED_CHECK_PRIVATE_LOGS'
371 exit 3
372 } finally {
373 if ($null -ne $connection) { $connection.Dispose() }
374 }