فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
feat(a02): export read-only Holoo schema metadata as DPAPI-protected local manifest
davoodmehraban89 committed
Oct 30, 2026 at 20:27 UTC
d67fbfd101ab3e909a4a1a756196486972163d1e
1 file changed
+355
-42
scripts/a02-isolated-schema-inventory.ps1
+355
-42
@@ -1,14 +1,25 @@
1
#requires -Version 5.1
2
<#
3
-A02: schema-only metadata from new isolated SQL DB. No financial rows, counts
4
-of business rows, raw SQL messages, schema names or file paths in STDOUT.
5
-Test mode is pure synthetic; Inspect never writes/creates databases.
3
+A02: read-only SQL schema inventory for a restored, isolated database.
4
+Inspect prints counts/hash only. PrivateManifest writes schema metadata only,
5
+encrypted with Windows DPAPI CurrentUser and a restrictive local file ACL.
6
+DecryptManifest creates a local ACL-restricted plaintext schema-only JSON file.
7
+No application/business rows are queried. No database writes are performed.
8
#>
9
[CmdletBinding()]
8
-param([ValidateSet('Test','Inspect')][string]$Mode='Test',
9
- [string]$InstanceName='FINORAMIG',[string]$DatabaseName='')
10
+param(
11
+ [ValidateSet('Test','Inspect','PrivateManifest','DecryptManifest')]
12
+ [string]$Mode='Test',
13
+ [string]$InstanceName='FINORAMIG',
14
+ [string]$DatabaseName='',
15
+ [string]$OutputPath='',
16
+ [string]$InputPath=''
17
+)
18
Set-StrictMode -Version Latest
19
$ErrorActionPreference='Stop'
20
+$script:ManifestHeader='FEP-A02-DPAPI-V1'
21
+$script:ManifestEntropy=[Text.Encoding]::UTF8.GetBytes('FactorEasyPro|A02|SchemaManifest|v1')
22
+
23
function Assert-Target([string]$instance,[string]$database){
24
if($instance -ceq 'FINORAMIG'){
25
if($database -cnotmatch '^FinoraHoloo_[0-9a-f]{32}$'){throw 'A02_ISOLATED_DB_REQUIRED'}
@@ -36,6 +47,297 @@ function Fingerprint([object[]]$rows){
47
return [BitConverter]::ToString($sha.ComputeHash($bytes)).Replace('-','').ToLowerInvariant()
48
}finally{$sha.Dispose()}
49
}
50
+function Assert-LocalFilePath([string]$value,[bool]$mustExist){
51
+ if([string]::IsNullOrWhiteSpace($value) -or
52
+ $value -notmatch '^[A-Za-z]:\\' -or
53
+ $value -match '[/\x00-\x1f<>\"|?*]' -or
54
+ $value.Substring(2).Contains(':')){throw 'A02_PRIVATE_PATH_NOT_LOCAL'}
55
+ foreach($segment in $value.Substring(3).Split('\')){
56
+ if([string]::IsNullOrWhiteSpace($segment) -or $segment -eq '.' -or
57
+ $segment -eq '..' -or $segment.EndsWith(' ') -or $segment.EndsWith('.')){
58
+ throw 'A02_PRIVATE_PATH_AMBIGUOUS'
59
+ }
60
+ }
61
+ $full=[IO.Path]::GetFullPath($value)
62
+ $drive=[IO.DriveInfo]::new($full.Substring(0,1))
63
+ if($drive.DriveType -ne [IO.DriveType]::Fixed -or -not $drive.IsReady){
64
+ throw 'A02_PRIVATE_PATH_REQUIRES_FIXED_LOCAL_DISK'
65
+ }
66
+ $directory=[IO.DirectoryInfo]::new([IO.Path]::GetDirectoryName($full))
67
+ if(-not $directory.Exists){throw 'A02_PRIVATE_PARENT_DIRECTORY_MISSING'}
68
+ $cursor=$directory
69
+ while($null -ne $cursor){
70
+ if(($cursor.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0){
71
+ throw 'A02_PRIVATE_PATH_REPARSE_POINT'
72
+ }
73
+ $cursor=$cursor.Parent
74
+ }
75
+ if($mustExist){
76
+ $file=[IO.FileInfo]::new($full)
77
+ if(-not $file.Exists -or $file.Length -lt 1 -or $file.Length -gt 67108864){
78
+ throw 'A02_PRIVATE_INPUT_FILE_INVALID'
79
+ }
80
+ if(($file.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0){
81
+ throw 'A02_PRIVATE_INPUT_REPARSE_POINT'
82
+ }
83
+ }else{
84
+ if([IO.File]::Exists($full) -or [IO.Directory]::Exists($full)){
85
+ throw 'A02_PRIVATE_OUTPUT_ALREADY_EXISTS'
86
+ }
87
+ }
88
+ return $full
89
+}
90
+function Write-RestrictedFile([string]$path,[byte[]]$bytes){
91
+ if($bytes.Length -lt 1 -or $bytes.Length -gt 67108864){throw 'A02_PRIVATE_OUTPUT_SIZE_INVALID'}
92
+ $full=Assert-LocalFilePath $path $false
93
+ $directory=[IO.Path]::GetDirectoryName($full)
94
+ $temporary=[IO.Path]::Combine($directory,'.a02-'+[guid]::NewGuid().ToString('N')+'.tmp')
95
+ try{
96
+ $stream=[IO.File]::Open($temporary,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::None)
97
+ $stream.Dispose()
98
+ $current=[Security.Principal.WindowsIdentity]::GetCurrent().User
99
+ $sidValues=@($current.Value,'S-1-5-18','S-1-5-32-544') | Select-Object -Unique
100
+ $acl=[Security.AccessControl.FileSecurity]::new()
101
+ $acl.SetAccessRuleProtection($true,$false)
102
+ $acl.SetOwner($current)
103
+ foreach($sidValue in $sidValues){
104
+ $sid=[Security.Principal.SecurityIdentifier]::new([string]$sidValue)
105
+ $rule=[Security.AccessControl.FileSystemAccessRule]::new(
106
+ $sid,[Security.AccessControl.FileSystemRights]::FullControl,
107
+ [Security.AccessControl.AccessControlType]::Allow)
108
+ [void]$acl.AddAccessRule($rule)
109
+ }
110
+ [IO.File]::SetAccessControl($temporary,$acl)
111
+ [IO.File]::WriteAllBytes($temporary,$bytes)
112
+ $check=[IO.File]::GetAccessControl($temporary)
113
+ if(-not $check.AreAccessRulesProtected){throw 'A02_PRIVATE_ACL_NOT_PROTECTED'}
114
+ $rules=@($check.GetAccessRules($true,$false,[Security.Principal.SecurityIdentifier]))
115
+ if($rules.Count -ne $sidValues.Count){throw 'A02_PRIVATE_ACL_RULE_COUNT_INVALID'}
116
+ foreach($entry in $rules){
117
+ if($entry.AccessControlType -ne [Security.AccessControl.AccessControlType]::Allow -or
118
+ $entry.FileSystemRights -ne [Security.AccessControl.FileSystemRights]::FullControl -or
119
+ $entry.IdentityReference.Value -notin $sidValues){
120
+ throw 'A02_PRIVATE_ACL_RULE_INVALID'
121
+ }
122
+ }
123
+ [IO.File]::Move($temporary,$full)
124
+ }finally{
125
+ if([IO.File]::Exists($temporary)){[IO.File]::Delete($temporary)}
126
+ }
127
+}
128
+function Get-SchemaData($connection){
129
+ $columnSql=@'
130
+SELECT s.name AS SchemaName,t.name AS TableName,c.name AS ColumnName,
131
+ ts.name AS TypeSchemaName,ty.name AS DataType,
132
+ c.column_id AS Ordinal,c.max_length AS MaxLength,
133
+ c.precision AS Precision,c.scale AS Scale,c.is_nullable AS IsNullable,
134
+ c.is_identity AS IsIdentity,c.is_computed AS IsComputed,
135
+ c.collation_name AS CollationName,c.is_rowguidcol AS IsRowGuid,
136
+ c.is_sparse AS IsSparse,c.is_filestream AS IsFileStream,
137
+ c.generated_always_type AS GeneratedAlwaysType
138
+FROM sys.tables AS t
139
+JOIN sys.schemas AS s ON s.schema_id=t.schema_id
140
+JOIN sys.columns AS c ON c.object_id=t.object_id
141
+JOIN sys.types AS ty ON ty.user_type_id=c.user_type_id
142
+JOIN sys.schemas AS ts ON ts.schema_id=ty.schema_id
143
+WHERE t.is_ms_shipped=0
144
+ORDER BY s.name,t.name,c.column_id;
145
+'@
146
+ $indexSql=@'
147
+SELECT s.name AS SchemaName,t.name AS TableName,i.index_id AS IndexId,
148
+ i.name AS IndexName,i.is_primary_key AS IsPrimaryKey,
149
+ i.is_unique AS IsUnique,i.type_desc AS IndexType,
150
+ i.is_disabled AS IsDisabled,i.has_filter AS HasFilter,
151
+ ic.key_ordinal AS KeyOrdinal,ic.index_column_id AS IndexColumnId,
152
+ ic.is_included_column AS IsIncludedColumn,
153
+ ic.is_descending_key AS IsDescendingKey,c.name AS ColumnName
154
+FROM sys.indexes AS i
155
+JOIN sys.tables AS t ON t.object_id=i.object_id
156
+JOIN sys.schemas AS s ON s.schema_id=t.schema_id
157
+JOIN sys.index_columns AS ic ON ic.object_id=i.object_id AND ic.index_id=i.index_id
158
+JOIN sys.columns AS c ON c.object_id=ic.object_id AND c.column_id=ic.column_id
159
+WHERE t.is_ms_shipped=0 AND i.index_id>0 AND i.is_hypothetical=0
160
+ AND (i.is_primary_key=1 OR i.is_unique=1)
161
+ORDER BY s.name,t.name,i.index_id,ic.index_column_id;
162
+'@
163
+ $foreignSql=@'
164
+SELECT fk.object_id AS ForeignKeyId,fk.name AS ForeignKeyName,
165
+ ps.name AS ParentSchema,pt.name AS ParentTable,
166
+ pc.name AS ParentColumn,rs.name AS ReferencedSchema,
167
+ rt.name AS ReferencedTable,rc.name AS ReferencedColumn,
168
+ fkc.constraint_column_id AS Ordinal,
169
+ fk.is_disabled AS IsDisabled,fk.is_not_trusted AS IsNotTrusted
170
+FROM sys.foreign_keys AS fk
171
+JOIN sys.foreign_key_columns AS fkc ON fkc.constraint_object_id=fk.object_id
172
+JOIN sys.tables AS pt ON pt.object_id=fk.parent_object_id
173
+JOIN sys.schemas AS ps ON ps.schema_id=pt.schema_id
174
+JOIN sys.columns AS pc ON pc.object_id=pt.object_id AND pc.column_id=fkc.parent_column_id
175
+JOIN sys.tables AS rt ON rt.object_id=fk.referenced_object_id
176
+JOIN sys.schemas AS rs ON rs.schema_id=rt.schema_id
177
+JOIN sys.columns AS rc ON rc.object_id=rt.object_id AND rc.column_id=fkc.referenced_column_id
178
+ORDER BY ps.name,pt.name,fk.object_id,fkc.constraint_column_id;
179
+'@
180
+ $metaSql=@'
181
+SELECT CAST(SERVERPROPERTY('ProductMajorVersion') AS int) AS EngineMajorVersion,
182
+ d.compatibility_level AS CompatibilityLevel,d.collation_name AS DatabaseCollation,
183
+ d.is_read_only AS IsReadOnly,d.recovery_model_desc AS RecoveryModel
184
+FROM sys.databases AS d WHERE d.name=DB_NAME();
185
+'@
186
+ $columnTable=$null;$indexTable=$null;$foreignTable=$null;$metaTable=$null
187
+ try{
188
+ foreach($spec in @(
189
+ @{Name='columnTable';Sql=$columnSql},
190
+ @{Name='indexTable';Sql=$indexSql},
191
+ @{Name='foreignTable';Sql=$foreignSql},
192
+ @{Name='metaTable';Sql=$metaSql}
193
+ )){
194
+ $cmd=$connection.CreateCommand();$cmd.CommandText=$spec.Sql;$cmd.CommandTimeout=120
195
+ $adapter=[Data.SqlClient.SqlDataAdapter]::new($cmd);$result=[Data.DataTable]::new()
196
+ try{[void]$adapter.Fill($result)}finally{$adapter.Dispose();$cmd.Dispose()}
197
+ Set-Variable -Name $spec.Name -Value $result -Scope Local
198
+ }
199
+ if($columnTable.Rows.Count -lt 2 -or $columnTable.Rows.Count -gt 200000 -or
200
+ $metaTable.Rows.Count -ne 1){throw 'A02_SCHEMA_SIZE_OR_METADATA_INVALID'}
201
+ $tableMap=@{};$tableOrder=[Collections.Generic.List[string]]::new()
202
+ foreach($r in $columnTable.Rows){
203
+ $schema=[string]$r['SchemaName'];$name=[string]$r['TableName']
204
+ $key=(Frame $schema)+(Frame $name)
205
+ if(-not $tableMap.ContainsKey($key)){
206
+ $tableMap[$key]=[ordered]@{
207
+ schema=$schema;name=$name
208
+ columns=[Collections.Generic.List[object]]::new()
209
+ indexes=[Collections.Generic.List[object]]::new()
210
+ foreignKeys=[Collections.Generic.List[object]]::new()
211
+ }
212
+ $tableOrder.Add($key)
213
+ }
214
+ $tableMap[$key].columns.Add([pscustomobject][ordered]@{
215
+ name=[string]$r['ColumnName'];typeSchema=[string]$r['TypeSchemaName']
216
+ dataType=[string]$r['DataType'];ordinal=[int]$r['Ordinal']
217
+ maxLength=[int]$r['MaxLength'];precision=[int]$r['Precision']
218
+ scale=[int]$r['Scale'];nullable=([int]$r['IsNullable'] -eq 1)
219
+ identity=([int]$r['IsIdentity'] -eq 1);computed=([int]$r['IsComputed'] -eq 1)
220
+ collation=if($r['CollationName'] -is [DBNull]){$null}else{[string]$r['CollationName']}
221
+ rowGuid=([int]$r['IsRowGuid'] -eq 1);sparse=([int]$r['IsSparse'] -eq 1)
222
+ fileStream=([int]$r['IsFileStream'] -eq 1)
223
+ generatedAlwaysType=[int]$r['GeneratedAlwaysType']
224
+ })
225
+ }
226
+ $indexMap=@{};$indexOrder=[Collections.Generic.List[string]]::new()
227
+ foreach($r in $indexTable.Rows){
228
+ $tableKey=(Frame ([string]$r['SchemaName']))+(Frame ([string]$r['TableName']))
229
+ $idxKey=$tableKey+(Frame ([string]$r['IndexId']))
230
+ if(-not $tableMap.ContainsKey($tableKey)){throw 'A02_SCHEMA_INDEX_PARENT_MISSING'}
231
+ if(-not $indexMap.ContainsKey($idxKey)){
232
+ $indexMap[$idxKey]=[ordered]@{
233
+ name=[string]$r['IndexName'];indexId=[int]$r['IndexId']
234
+ primaryKey=([int]$r['IsPrimaryKey'] -eq 1)
235
+ unique=([int]$r['IsUnique'] -eq 1);type=[string]$r['IndexType']
236
+ disabled=([int]$r['IsDisabled'] -eq 1);filtered=([int]$r['HasFilter'] -eq 1)
237
+ keyColumns=[Collections.Generic.List[object]]::new()
238
+ includedColumns=[Collections.Generic.List[string]]::new()
239
+ }
240
+ $indexOrder.Add($idxKey)
241
+ $tableMap[$tableKey].indexes.Add($indexMap[$idxKey])
242
+ }
243
+ if([int]$r['IsIncludedColumn'] -eq 1){
244
+ $indexMap[$idxKey].includedColumns.Add([string]$r['ColumnName'])
245
+ }elseif([int]$r['KeyOrdinal'] -gt 0){
246
+ $indexMap[$idxKey].keyColumns.Add([pscustomobject]@{
247
+ name=[string]$r['ColumnName'];ordinal=[int]$r['KeyOrdinal']
248
+ descending=([int]$r['IsDescendingKey'] -eq 1)
249
+ })
250
+ }
251
+ }
252
+ $foreignMap=@{};$foreignOrder=[Collections.Generic.List[string]]::new()
253
+ foreach($r in $foreignTable.Rows){
254
+ $parentKey=(Frame ([string]$r['ParentSchema']))+(Frame ([string]$r['ParentTable']))
255
+ $fkKey=$parentKey+(Frame ([string]$r['ForeignKeyId']))
256
+ if(-not $tableMap.ContainsKey($parentKey)){throw 'A02_SCHEMA_FOREIGN_KEY_PARENT_MISSING'}
257
+ if(-not $foreignMap.ContainsKey($fkKey)){
258
+ $foreignMap[$fkKey]=[ordered]@{
259
+ name=[string]$r['ForeignKeyName']
260
+ referencedSchema=[string]$r['ReferencedSchema']
261
+ referencedTable=[string]$r['ReferencedTable']
262
+ disabled=([int]$r['IsDisabled'] -eq 1)
263
+ notTrusted=([int]$r['IsNotTrusted'] -eq 1)
264
+ columns=[Collections.Generic.List[object]]::new()
265
+ }
266
+ $foreignOrder.Add($fkKey)
267
+ $tableMap[$parentKey].foreignKeys.Add($foreignMap[$fkKey])
268
+ }
269
+ $foreignMap[$fkKey].columns.Add([pscustomobject]@{
270
+ ordinal=[int]$r['Ordinal'];column=[string]$r['ParentColumn']
271
+ referencedColumn=[string]$r['ReferencedColumn']
272
+ })
273
+ }
274
+ $tables=[Collections.Generic.List[object]]::new()
275
+ foreach($key in $tableOrder){$tables.Add($tableMap[$key])}
276
+ $schemaObject=[ordered]@{tables=$tables}
277
+ $canonical=ConvertTo-Json -InputObject $schemaObject -Depth 20 -Compress
278
+ $sha=[Security.Cryptography.SHA256]::Create()
279
+ try{
280
+ $fingerprint=[BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($canonical))).Replace('-','').ToLowerInvariant()
281
+ }finally{$sha.Dispose()}
282
+ $columnCount=[int]$columnTable.Rows.Count
283
+ $tableCount=[int]$tables.Count
284
+ $indexCount=0;$primaryCount=0;$foreignCount=0
285
+ foreach($t in $tables){
286
+ foreach($idx in $t.indexes){$indexCount++;if($idx.primaryKey){$primaryCount++}}
287
+ $foreignCount+=$t.foreignKeys.Count
288
+ }
289
+ $manifest=[pscustomobject][ordered]@{
290
+ format='factor-easypro-a02-schema-manifest';formatVersion=1
291
+ generatedUtc=[DateTime]::UtcNow.ToString('o')
292
+ engineMajorVersion=[int]$metaTable.Rows[0]['EngineMajorVersion']
293
+ compatibilityLevel=[int]$metaTable.Rows[0]['CompatibilityLevel']
294
+ databaseCollation=[string]$metaTable.Rows[0]['DatabaseCollation']
295
+ isReadOnly=([int]$metaTable.Rows[0]['IsReadOnly'] -eq 1)
296
+ recoveryModel=[string]$metaTable.Rows[0]['RecoveryModel']
297
+ schemaFingerprintSha256=$fingerprint
298
+ tableCount=$tableCount;columnCount=$columnCount
299
+ uniqueIndexCount=$indexCount;primaryKeyCount=$primaryCount
300
+ foreignKeyCount=$foreignCount
301
+ userRowsRead=$false;databaseModified=$false;canImport=$false
302
+ tables=$tables
303
+ }
304
+ return $manifest
305
+ }finally{
306
+ foreach($item in @($columnTable,$indexTable,$foreignTable,$metaTable)){
307
+ if($null -ne $item){$item.Dispose()}
308
+ }
309
+ }
310
+}
311
+function Read-EncryptedManifest([string]$path){
312
+ $full=Assert-LocalFilePath $path $true
313
+ $raw=[IO.File]::ReadAllBytes($full)
314
+ $headerBytes=[Text.Encoding]::ASCII.GetBytes($script:ManifestHeader)
315
+ if($raw.Length -le ($headerBytes.Length+1)){throw 'A02_PRIVATE_MANIFEST_TRUNCATED'}
316
+ $header=[Text.Encoding]::ASCII.GetString($raw,0,$headerBytes.Length)
317
+ if($header -cne $script:ManifestHeader -or $raw[$headerBytes.Length] -ne 10){
318
+ throw 'A02_PRIVATE_MANIFEST_HEADER_INVALID'
319
+ }
320
+ $cipherLength=$raw.Length-$headerBytes.Length-1
321
+ $cipher=New-Object byte[] $cipherLength
322
+ [Buffer]::BlockCopy($raw,$headerBytes.Length+1,$cipher,0,$cipherLength)
323
+ Add-Type -AssemblyName System.Security -ErrorAction Stop
324
+ $plain=[Security.Cryptography.ProtectedData]::Unprotect(
325
+ $cipher,$script:ManifestEntropy,[Security.Cryptography.DataProtectionScope]::CurrentUser)
326
+ $json=[Text.Encoding]::UTF8.GetString($plain)
327
+ $manifest=$json | ConvertFrom-Json
328
+ if($manifest.format -cne 'factor-easypro-a02-schema-manifest' -or
329
+ [int]$manifest.formatVersion -ne 1 -or
330
+ [string]$manifest.schemaFingerprintSha256 -cnotmatch '^[0-9a-f]{64}$' -or
331
+ [int]$manifest.tableCount -lt 1 -or
332
+ [int]$manifest.columnCount -lt 2 -or
333
+ $manifest.userRowsRead -ne $false -or
334
+ $manifest.databaseModified -ne $false -or
335
+ $manifest.canImport -ne $false){
336
+ throw 'A02_PRIVATE_MANIFEST_CONTRACT_INVALID'
337
+ }
338
+ return ,$plain
339
+}
340
+
341
if($Mode -eq 'Test'){
342
Assert-Target 'FINORAMIG' 'FinoraHoloo_0123456789abcdef0123456789abcdef'
343
Assert-Target 'FinoraA02_0123456789ab' 'A02Restore_0123456789ab'
@@ -54,9 +356,25 @@ if($Mode -eq 'Test'){
356
if((Fingerprint $rows) -cne $h){throw 'A02_FINGERPRINT_NOT_ORDER_INDEPENDENT'}
357
$rows[0].ColumnName='changed'
358
if((Fingerprint $rows) -ceq $h){throw 'A02_FINGERPRINT_NOT_CHANGE_SENSITIVE'}
57
- [pscustomobject]@{status='schema-fingerprint-selftest-passed';sqlOpened=$false;userRowsRead=$false;databaseModified=$false;canImport=$false}|ConvertTo-Json -Compress
359
+ [pscustomobject]@{
360
+ status='schema-fingerprint-selftest-passed';sqlOpened=$false
361
+ userRowsRead=$false;databaseModified=$false;canImport=$false
362
+ }|ConvertTo-Json -Compress
363
+ return
364
+}
365
+
366
+if($Mode -eq 'DecryptManifest'){
367
+ try{
368
+ if([string]::IsNullOrWhiteSpace($InputPath) -or [string]::IsNullOrWhiteSpace($OutputPath)){
369
+ throw 'A02_PRIVATE_MANIFEST_PATHS_REQUIRED'
370
+ }
371
+ $plain=Read-EncryptedManifest $InputPath
372
+ Write-RestrictedFile $OutputPath $plain
373
+ [pscustomobject]@{status='private-schema-manifest-decrypted';plaintextFileAclRestricted=$true;userRowsRead=$false;databaseModified=$false;canImport=$false}|ConvertTo-Json -Compress
374
+ }catch{Write-Error 'A02_PRIVATE_MANIFEST_DECRYPT_FAILED';exit 2}
375
return
376
}
377
+
378
$conn=$null
379
try{
380
Assert-Target $InstanceName $DatabaseName
@@ -70,43 +388,38 @@ try{
388
$status=$check.ExecuteScalar();$check.Dispose()
389
if($null -eq $status -or [string]$status -cne 'ONLINE'){throw 'A02_RESTORE_NOT_ONLINE'}
390
$conn.ChangeDatabase($DatabaseName)
73
- # System catalogs ONLY; never reads application tables or business rows.
74
- $sql=@'
75
-SELECT s.name AS SchemaName,t.name AS TableName,c.name AS ColumnName,
76
- ty.name AS DataType,c.column_id AS Ordinal,c.max_length AS MaxLength,
77
- c.precision AS Precision,c.scale AS Scale,c.is_nullable AS IsNullable,
78
- c.is_identity AS IsIdentity,c.is_computed AS IsComputed
79
-FROM sys.tables AS t
80
-JOIN sys.schemas AS s ON s.schema_id=t.schema_id
81
-JOIN sys.columns AS c ON c.object_id=t.object_id
82
-JOIN sys.types AS ty ON ty.user_type_id=c.user_type_id
83
-WHERE t.is_ms_shipped=0 ORDER BY s.name,t.name,c.column_id;
84
-'@
85
- $cmd=$conn.CreateCommand();$cmd.CommandText=$sql;$cmd.CommandTimeout=120
86
- $adapter=[Data.SqlClient.SqlDataAdapter]::new($cmd)
87
- $table=[Data.DataTable]::new()
88
- try{[void]$adapter.Fill($table)}finally{$adapter.Dispose();$cmd.Dispose()}
89
- if($table.Rows.Count -lt 2 -or $table.Rows.Count -gt 200000){throw 'A02_SCHEMA_SIZE_INVALID'}
90
- $columns=[Collections.Generic.List[object]]::new()
91
- $tables=[Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal)
92
- foreach($r in $table.Rows){
93
- $o=[pscustomobject]@{
94
- SchemaName=[string]$r['SchemaName'];TableName=[string]$r['TableName']
95
- ColumnName=[string]$r['ColumnName'];DataType=[string]$r['DataType']
96
- Ordinal=[int]$r['Ordinal'];MaxLength=[int]$r['MaxLength']
97
- Precision=[int]$r['Precision'];Scale=[int]$r['Scale']
98
- IsNullable=[int]$r['IsNullable'];IsIdentity=[int]$r['IsIdentity']
99
- IsComputed=[int]$r['IsComputed']
100
- }
101
- $columns.Add($o);[void]$tables.Add((Frame $o.SchemaName)+(Frame $o.TableName))
391
+ $manifest=Get-SchemaData $conn
392
+ if($Mode -eq 'Inspect'){
393
+ [pscustomobject]@{
394
+ status='isolated-schema-inventoried'
395
+ fingerprintSha256=$manifest.schemaFingerprintSha256
396
+ tableCount=$manifest.tableCount;columnCount=$manifest.columnCount
397
+ primaryKeyCount=$manifest.primaryKeyCount;foreignKeyCount=$manifest.foreignKeyCount
398
+ userRowsRead=$false;databaseModified=$false;canImport=$false
399
+ }|ConvertTo-Json -Compress
400
+ }else{
401
+ if([string]::IsNullOrWhiteSpace($OutputPath)){throw 'A02_PRIVATE_OUTPUT_PATH_REQUIRED'}
402
+ $json=ConvertTo-Json -InputObject $manifest -Depth 20
403
+ $plain=[Text.Encoding]::UTF8.GetBytes($json)
404
+ if($plain.Length -gt 33554432){throw 'A02_PRIVATE_MANIFEST_TOO_LARGE'}
405
+ Add-Type -AssemblyName System.Security -ErrorAction Stop
406
+ $cipher=[Security.Cryptography.ProtectedData]::Protect(
407
+ $plain,$script:ManifestEntropy,[Security.Cryptography.DataProtectionScope]::CurrentUser)
408
+ $header=[Text.Encoding]::ASCII.GetBytes($script:ManifestHeader)
409
+ $payload=New-Object byte[] ($header.Length+1+$cipher.Length)
410
+ [Buffer]::BlockCopy($header,0,$payload,0,$header.Length)
411
+ $payload[$header.Length]=10
412
+ [Buffer]::BlockCopy($cipher,0,$payload,$header.Length+1,$cipher.Length)
413
+ Write-RestrictedFile $OutputPath $payload
414
+ [pscustomobject]@{
415
+ status='private-schema-manifest-encrypted'
416
+ tableCount=$manifest.tableCount;columnCount=$manifest.columnCount
417
+ primaryKeyCount=$manifest.primaryKeyCount;foreignKeyCount=$manifest.foreignKeyCount
418
+ dpapiScope='CurrentUser';fileAclRestricted=$true
419
+ userRowsRead=$false;databaseModified=$false;canImport=$false
420
+ }|ConvertTo-Json -Compress
421
}
103
- [pscustomobject]@{
104
- status='isolated-schema-inventoried'
105
- fingerprintSha256=(Fingerprint ($columns.ToArray()))
106
- tableCount=$tables.Count;columnCount=$columns.Count
107
- userRowsRead=$false;databaseModified=$false;canImport=$false
108
- }|ConvertTo-Json -Compress
422
}catch{
110
- Write-Error 'A02_SCHEMA_INVENTORY_FAILED'
423
+ Write-Error 'A02_SCHEMA_INVENTORY_OR_PRIVATE_EXPORT_FAILED'
424
exit 2
425
}finally{if($null -ne $conn){$conn.Dispose()}}