-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQLSyncCommon.psm1
More file actions
907 lines (747 loc) · 26.5 KB
/
SQLSyncCommon.psm1
File metadata and controls
907 lines (747 loc) · 26.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
<#
.SYNOPSIS
Gemeinsames Modul für SQLSync - Firebird to MSSQL Synchronizer.
.DESCRIPTION
Enthält wiederverwendbare Funktionen für:
- Credential Manager Zugriff
- Konfigurationsverwaltung
- Connection String Building
- Sichere Datenbankverbindungen mit automatischem Cleanup
.NOTES
Version: 1.0.0
Importieren mit: Import-Module (Join-Path $PSScriptRoot "SQLSyncCommon.psm1") -Force
.LINK
https://github.com/gitnol/PSFirebirdToMSSQL
#>
#region Credential Manager
<#
.SYNOPSIS
Liest Credentials aus dem Windows Credential Manager.
.PARAMETER Target
Der Name des Credential-Eintrags (z.B. "SQLSync_Firebird").
.OUTPUTS
PSCustomObject mit Username und Password, oder $null wenn nicht gefunden.
.EXAMPLE
$cred = Get-StoredCredential -Target "SQLSync_Firebird"
if ($cred) { Write-Host "User: $($cred.Username)" }
#>
function Get-StoredCredential {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$Target
)
# Prüfen ob Typ schon existiert (verhindert Fehler bei erneutem Laden)
if (-not ('CredManager.Util' -as [type])) {
$Source = @'
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace CredManager {
public static class Util {
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool CredRead(string target, int type, int reserved, out IntPtr credential);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern void CredFree(IntPtr credential);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct CREDENTIAL {
public int Flags;
public int Type;
public string TargetName;
public string Comment;
public long LastWritten;
public int CredentialBlobSize;
public IntPtr CredentialBlob;
public int Persist;
public int AttributeCount;
public IntPtr Attributes;
public string TargetAlias;
public string UserName;
}
}
}
'@
Add-Type -TypeDefinition $Source -Language CSharp
}
$CredPtr = [IntPtr]::Zero
$Success = [CredManager.Util]::CredRead($Target, 1, 0, [ref]$CredPtr)
if (-not $Success) { return $null }
try {
$Cred = [System.Runtime.InteropServices.Marshal]::PtrToStructure($CredPtr, [Type][CredManager.Util+CREDENTIAL])
$Password = ""
if ($Cred.CredentialBlobSize -gt 0) {
$Password = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Cred.CredentialBlob, $Cred.CredentialBlobSize / 2)
}
return [PSCustomObject]@{
Username = $Cred.UserName
Password = $Password
}
}
finally {
[CredManager.Util]::CredFree($CredPtr)
}
}
#endregion
#region Configuration
<#
.SYNOPSIS
Lädt und validiert die SQLSync Konfigurationsdatei.
.PARAMETER ConfigPath
Pfad zur JSON-Konfigurationsdatei.
.PARAMETER SchemaPath
Optional: Pfad zur JSON-Schema-Datei für Validierung.
.OUTPUTS
Hashtable mit allen Konfigurationswerten inkl. aufgelöster Credentials.
.EXAMPLE
$config = Get-SQLSyncConfig -ConfigPath ".\config.json"
#>
function Get-SQLSyncConfig {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$ConfigPath,
[Parameter()]
[string]$SchemaPath
)
# Datei prüfen
if (-not (Test-Path $ConfigPath)) {
throw "Konfigurationsdatei nicht gefunden: $ConfigPath"
}
# JSON laden
try {
$JsonContent = Get-Content -Path $ConfigPath -Raw -ErrorAction Stop
$Config = $JsonContent | ConvertFrom-Json -ErrorAction Stop
}
catch {
throw "Fehler beim Parsen der Konfiguration: $($_.Exception.Message)"
}
# Optional: Schema-Validierung (PowerShell 6+)
if ($SchemaPath -and (Test-Path $SchemaPath)) {
try {
$ValidationResult = Test-Json -Json $JsonContent -SchemaFile $SchemaPath -ErrorAction Stop
if (-not $ValidationResult) {
throw "Konfiguration entspricht nicht dem Schema."
}
}
catch {
Write-Warning "Schema-Validierung fehlgeschlagen: $($_.Exception.Message)"
}
}
# Defaults anwenden und Hashtable bauen
$Result = @{
# General Settings
GlobalTimeout = Get-ConfigValue $Config.General "GlobalTimeout" 7200
RecreateStagingTable = Get-ConfigValue $Config.General "RecreateStagingTable" $false
ForceFullSync = Get-ConfigValue $Config.General "ForceFullSync" $false
RecreateStoredProcedure = Get-ConfigValue $Config.General "RecreateStoredProcedure" $false
NumberOfThreads = Get-ConfigValue $Config.General "NumberOfThreads" 4
RunSanityCheck = Get-ConfigValue $Config.General "RunSanityCheck" $true
MaxRetries = Get-ConfigValue $Config.General "MaxRetries" 3
RetryDelaySeconds = Get-ConfigValue $Config.General "RetryDelaySeconds" 10
DeleteLogOlderThanDays = Get-ConfigValue $Config.General "DeleteLogOlderThanDays" 30
CleanupOrphans = Get-ConfigValue $Config.General "CleanupOrphans" $false
OrphanCleanupBatchSize = Get-ConfigValue $Config.General "OrphanCleanupBatchSize" 50000
# Column Configuration (NEU in v2.10)
IdColumn = Get-ConfigValue $Config.General "IdColumn" "ID"
TimestampColumns = @(Get-ConfigValue $Config.General "TimestampColumns" @("GESPEICHERT"))
# Firebird Settings
FBServer = $Config.Firebird.Server
FBDatabase = $Config.Firebird.Database
FBPort = Get-ConfigValue $Config.Firebird "Port" 3050
FBCharset = Get-ConfigValue $Config.Firebird "Charset" "UTF8"
DllPath = $Config.Firebird.DllPath
# MSSQL Settings
MSSQLServer = $Config.MSSQL.Server
MSSQLDatabase = $Config.MSSQL.Database
MSSQLIntSec = Get-ConfigValue $Config.MSSQL "Integrated Security" $false
MSSQLPrefix = Get-ConfigValue $Config.MSSQL "Prefix" ""
MSSQLSuffix = Get-ConfigValue $Config.MSSQL "Suffix" ""
# Tables
Tables = @($Config.Tables)
# Table Overrides (NEU in v2.10)
TableOverrides = @{}
# Raw Config für Zugriff auf weitere Properties
RawConfig = $Config
}
# TableOverrides laden (falls vorhanden)
if ($Config.PSObject.Properties.Match("TableOverrides").Count -gt 0 -and $null -ne $Config.TableOverrides) {
foreach ($prop in $Config.TableOverrides.PSObject.Properties) {
$Result.TableOverrides[$prop.Name] = @{
IdColumn = Get-ConfigValue $prop.Value "IdColumn" $null
TimestampColumn = Get-ConfigValue $prop.Value "TimestampColumn" $null
}
}
}
# Validierungen
if ($Result.GlobalTimeout -le 0) {
throw "GlobalTimeout muss größer als 0 sein."
}
if (-not $Result.Tables -or $Result.Tables.Count -eq 0) {
throw "Keine Tabellen in der Konfiguration definiert."
}
if ($Result.OrphanCleanupBatchSize -lt 1000) {
throw "OrphanCleanupBatchSize muss mindestens 1000 sein."
}
return $Result
}
<#
.SYNOPSIS
Hilfsfunktion zum sicheren Auslesen von Config-Werten mit Default.
#>
function Get-ConfigValue {
param(
[object]$ConfigSection,
[string]$PropertyName,
[object]$DefaultValue
)
if ($null -eq $ConfigSection) { return $DefaultValue }
if ($ConfigSection.PSObject.Properties.Match($PropertyName).Count -gt 0) {
$Value = $ConfigSection.$PropertyName
if ($null -ne $Value) { return $Value }
}
return $DefaultValue
}
#endregion
#region Credentials Resolution
<#
.SYNOPSIS
Löst Firebird-Credentials auf (Credential Manager -> Config Fallback).
.PARAMETER Config
Die geladene Konfiguration (RawConfig).
.OUTPUTS
Hashtable mit Username und Password.
#>
function Resolve-FirebirdCredentials {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[object]$Config
)
# 1. Versuch: Credential Manager
$Cred = Get-StoredCredential -Target "SQLSync_Firebird"
if ($Cred) {
Write-Host "[Credentials] Firebird: Credential Manager" -ForegroundColor Green
return @{
Username = $Cred.Username
Password = $Cred.Password
Source = "CredentialManager"
}
}
# 2. Fallback: config.json
if ($Config.Firebird.Password) {
$Username = if ($Config.Firebird.User) { $Config.Firebird.User } else { "SYSDBA" }
Write-Host "[Credentials] Firebird: config.json (WARNUNG: unsicher!)" -ForegroundColor Yellow
return @{
Username = $Username
Password = $Config.Firebird.Password
Source = "ConfigFile"
}
}
throw "Keine Firebird Credentials gefunden! Führe Setup_Credentials.ps1 aus."
}
<#
.SYNOPSIS
Löst MSSQL-Credentials auf (Windows Auth -> Credential Manager -> Config Fallback).
.PARAMETER Config
Die geladene Konfiguration (RawConfig).
.OUTPUTS
Hashtable mit Username, Password und IntegratedSecurity Flag.
#>
function Resolve-MSSQLCredentials {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[object]$Config
)
# Windows Authentication?
$IntSec = Get-ConfigValue $Config.MSSQL "Integrated Security" $false
if ($IntSec) {
Write-Host "[Credentials] SQL Server: Windows Authentication" -ForegroundColor Green
return @{
Username = $null
Password = $null
IntegratedSecurity = $true
Source = "WindowsAuth"
}
}
# 1. Versuch: Credential Manager
$Cred = Get-StoredCredential -Target "SQLSync_MSSQL"
if ($Cred) {
Write-Host "[Credentials] SQL Server: Credential Manager" -ForegroundColor Green
return @{
Username = $Cred.Username
Password = $Cred.Password
IntegratedSecurity = $false
Source = "CredentialManager"
}
}
# 2. Fallback: config.json
if ($Config.MSSQL.Password) {
Write-Host "[Credentials] SQL Server: config.json (WARNUNG: unsicher!)" -ForegroundColor Yellow
return @{
Username = $Config.MSSQL.Username
Password = $Config.MSSQL.Password
IntegratedSecurity = $false
Source = "ConfigFile"
}
}
throw "Keine SQL Server Credentials gefunden! Führe Setup_Credentials.ps1 aus oder aktiviere 'Integrated Security'."
}
#endregion
#region Connection Strings
<#
.SYNOPSIS
Erstellt einen Firebird Connection String.
#>
function New-FirebirdConnectionString {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$Server,
[Parameter(Mandatory)]
[string]$Database,
[Parameter(Mandatory)]
[string]$Username,
[Parameter(Mandatory)]
[AllowEmptyString()]
$Password, # Kein Typ-Constraint - akzeptiert String oder SecureString
[int]$Port = 3050,
[string]$Charset = "UTF8"
)
# Falls SecureString übergeben wurde, konvertieren
$PlainPassword = $Password
if ($Password -is [System.Security.SecureString]) {
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)
$PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR)
}
return "User=$Username;Password=$PlainPassword;Database=$Database;DataSource=$Server;Port=$Port;Dialect=3;Charset=$Charset;"
}
<#
.SYNOPSIS
Erstellt einen MSSQL Connection String.
#>
function New-MSSQLConnectionString {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$Server,
[Parameter(Mandatory)]
[string]$Database,
[AllowEmptyString()]
[AllowNull()]
$Username,
[AllowEmptyString()]
[AllowNull()]
$Password, # Kein Typ-Constraint - akzeptiert String oder SecureString
[bool]$IntegratedSecurity = $false
)
if ($IntegratedSecurity) {
return "Server=$Server;Database=$Database;Integrated Security=True;"
}
else {
# Falls SecureString übergeben wurde, konvertieren
$PlainPassword = $Password
if ($Password -is [System.Security.SecureString]) {
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)
$PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR)
}
return "Server=$Server;Database=$Database;User Id=$Username;Password=$PlainPassword;"
}
}
#endregion
#region Firebird Driver
<#
.SYNOPSIS
Lädt den Firebird .NET Treiber.
.PARAMETER DllPath
Konfigurierter Pfad zur DLL.
.PARAMETER ScriptDir
Skript-Verzeichnis für relative Pfade.
.OUTPUTS
Der aufgelöste Pfad zur DLL.
#>
<#
.SYNOPSIS
Lädt den Firebird .NET Treiber (Version 10.3.4).
Installiert ihn bei Bedarf systemweit in C:\ProgramData (benötigt Admin-Rechte).
.PARAMETER DllPath
Optional: Ein expliziter Pfad zur DLL (überschreibt die Automatik).
.PARAMETER ScriptDir
Optional: Skript-Verzeichnis für relative Pfade.
.OUTPUTS
Der aufgelöste Pfad zur DLL.
#>
function Initialize-FirebirdDriver {
[CmdletBinding()]
param(
[string]$DllPath,
[string]$ScriptDir
)
# Konstanten
$PackageVersion = "10.3.4"
$PackageName = "FirebirdSql.Data.FirebirdClient"
$CentralInstallDir = "$env:ProgramData\SQLSync\Drivers\$PackageName.$PackageVersion"
# Helper: Admin-Check
function Test-IsAdministrator {
$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object System.Security.Principal.WindowsPrincipal($identity)
return $principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
}
# --- SCHRITT A: Prüfen, ob Assembly schon geladen ist (Verhindert Fehler) ---
$LoadedAssembly = [AppDomain]::CurrentDomain.GetAssemblies() |
Where-Object { $_.GetName().Name -eq $PackageName } |
Select-Object -First 1
if ($LoadedAssembly) {
Write-Host "[Driver] Firebird .NET Provider ist bereits aktiv (aus Speicher)." -ForegroundColor DarkGray
# Wir nutzen die Version, die schon da ist, um Konflikte zu vermeiden
return $LoadedAssembly.Location
}
# --- SCHRITT B: Pfad suchen (wenn noch nicht geladen) ---
$CandidatePaths = @()
if (-not [string]::IsNullOrWhiteSpace($DllPath)) {
$CandidatePaths += $DllPath
if ($ScriptDir) { $CandidatePaths += Join-Path $ScriptDir $DllPath }
}
# Priorisiere .NET 8.0 für moderne Systeme
$CandidatePaths += Join-Path $CentralInstallDir "lib\net8.0\$PackageName.dll"
$CandidatePaths += Join-Path $CentralInstallDir "lib\netstandard2.1\$PackageName.dll"
$ResolvedPath = $null
foreach ($Path in $CandidatePaths) {
if (Test-Path $Path) {
$ResolvedPath = $Path
break
}
}
# --- SCHRITT C: Installieren (wenn Datei fehlt) ---
if (-not $ResolvedPath) {
Write-Host "Firebird Treiber ($PackageVersion) nicht gefunden." -ForegroundColor Yellow
if (-not (Test-IsAdministrator)) {
throw "Der Firebird-Treiber fehlt in $CentralInstallDir. Bitte einmalig als ADMINISTRATOR ausführen."
}
Write-Host "Starte systemweiten Download..." -ForegroundColor Cyan
if (-not (Test-Path $CentralInstallDir)) { New-Item -ItemType Directory -Path $CentralInstallDir -Force | Out-Null }
$ZipPath = Join-Path $CentralInstallDir "package.zip"
try {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -Uri "https://globalcdn.nuget.org/packages/firebirdsql.data.firebirdclient.10.3.4.nupkg" -OutFile $ZipPath -ErrorAction Stop
Expand-Archive -Path $ZipPath -DestinationPath $CentralInstallDir -Force
Remove-Item -Path $ZipPath -Force -ErrorAction SilentlyContinue
# Neu aufgelöster Pfad
$ResolvedPath = Join-Path $CentralInstallDir "lib\net8.0\$PackageName.dll"
}
catch {
throw "Download fehlgeschlagen: $($_.Exception.Message)"
}
}
# --- SCHRITT D: Laden ---
if (-not $ResolvedPath -or -not (Test-Path $ResolvedPath)) {
throw "Treiber konnte nicht bereitgestellt werden."
}
try {
Add-Type -Path $ResolvedPath
Write-Host "[Driver] Firebird .NET Provider geladen: $ResolvedPath" -ForegroundColor DarkGray
}
catch {
# Falls Add-Type trotz Vorab-Check fehlschlägt (sehr selten)
throw "Fehler beim Laden der Assembly ($ResolvedPath): $($_.Exception.Message)"
}
return $ResolvedPath
}
#endregion
#region Safe Database Operations
<#
.SYNOPSIS
Führt eine Aktion mit einer Firebird-Verbindung aus und garantiert Cleanup.
.DESCRIPTION
Öffnet eine Verbindung, führt den ScriptBlock aus und schließt die Verbindung
im finally-Block - auch bei Fehlern.
.PARAMETER ConnectionString
Der Firebird Connection String.
.PARAMETER Action
Der auszuführende ScriptBlock. Erhält $Connection als Parameter.
.EXAMPLE
Invoke-WithFirebirdConnection -ConnectionString $cs -Action {
param($conn)
$cmd = $conn.CreateCommand()
$cmd.CommandText = "SELECT * FROM MYTABLE"
$cmd.ExecuteReader()
}
#>
function Invoke-WithFirebirdConnection {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$ConnectionString,
[Parameter(Mandatory)]
[scriptblock]$Action
)
$Connection = $null
try {
$Connection = New-Object FirebirdSql.Data.FirebirdClient.FbConnection($ConnectionString)
$Connection.Open()
# ScriptBlock ausführen mit Connection als Parameter
& $Action $Connection
}
finally {
if ($Connection) {
try { $Connection.Close() } catch { }
try { $Connection.Dispose() } catch { }
}
}
}
<#
.SYNOPSIS
Führt eine Aktion mit einer MSSQL-Verbindung aus und garantiert Cleanup.
.PARAMETER ConnectionString
Der MSSQL Connection String.
.PARAMETER Action
Der auszuführende ScriptBlock. Erhält $Connection als Parameter.
#>
function Invoke-WithMSSQLConnection {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$ConnectionString,
[Parameter(Mandatory)]
[scriptblock]$Action
)
$Connection = $null
try {
$Connection = New-Object System.Data.SqlClient.SqlConnection($ConnectionString)
$Connection.Open()
& $Action $Connection
}
finally {
if ($Connection) {
try { $Connection.Close() } catch { }
try { $Connection.Dispose() } catch { }
}
}
}
<#
.SYNOPSIS
Schließt und disposed eine Datenbankverbindung sicher.
.DESCRIPTION
Kann für beliebige Connection-Objekte verwendet werden.
Fängt alle Exceptions ab um Folgefehler zu vermeiden.
.PARAMETER Connection
Das zu schließende Connection-Objekt.
#>
function Close-DatabaseConnection {
[CmdletBinding()]
param(
[Parameter()]
[object]$Connection
)
if ($null -eq $Connection) { return }
try { $Connection.Close() } catch { }
try { $Connection.Dispose() } catch { }
}
#endregion
#region Logging Helpers
<#
.SYNOPSIS
Schreibt eine formatierte Status-Nachricht.
#>
function Write-SyncStatus {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$TableName,
[Parameter(Mandatory)]
[string]$Message,
[ValidateSet("Info", "Success", "Warning", "Error")]
[string]$Level = "Info"
)
$Color = switch ($Level) {
"Success" { "Green" }
"Warning" { "Yellow" }
"Error" { "Red" }
default { "Gray" }
}
Write-Host "[$TableName] $Message" -ForegroundColor $Color
}
#endregion
#region Type Mapping
<#
.SYNOPSIS
Mappt einen .NET-Datentyp auf den entsprechenden SQL Server Datentyp.
.PARAMETER DotNetTypeName
Der Name des .NET-Typs (z.B. "Int32", "String").
.PARAMETER Size
Die Spaltengröße (relevant für String-Typen).
.OUTPUTS
Der SQL Server Datentyp als String.
#>
function ConvertTo-SqlServerType {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$DotNetTypeName,
[int]$Size = 0
)
switch ($DotNetTypeName) {
"Int16" { return "SMALLINT" }
"Int32" { return "INT" }
"Int64" { return "BIGINT" }
"String" {
if ($Size -gt 0 -and $Size -le 4000) {
return "NVARCHAR($Size)"
}
else {
return "NVARCHAR(MAX)"
}
}
"DateTime" { return "DATETIME2" }
"TimeSpan" { return "TIME" }
"Decimal" { return "DECIMAL(18,4)" }
"Double" { return "FLOAT" }
"Single" { return "REAL" }
"Byte[]" { return "VARBINARY(MAX)" }
"Boolean" { return "BIT" }
"Guid" { return "UNIQUEIDENTIFIER" }
default { return "NVARCHAR(MAX)" }
}
}
#endregion
#region Table Column Configuration
<#
.SYNOPSIS
Ermittelt die ID- und Timestamp-Spalten für eine Tabelle.
.DESCRIPTION
Diese Funktion kapselt die gesamte Logik zur Ermittlung der richtigen
Spalten für die Sync-Strategie:
1. Prüft TableOverrides für tabellenspezifische Konfiguration
2. Fällt auf globale Defaults zurück
3. Prüft welche Spalten tatsächlich in der Tabelle existieren
4. Leitet die Sync-Strategie ab
.PARAMETER TableName
Name der zu prüfenden Tabelle.
.PARAMETER Config
Das Config-Objekt aus Get-SQLSyncConfig.
.PARAMETER ActualColumns
Array mit den tatsächlichen Spaltennamen der Tabelle.
.OUTPUTS
Hashtable mit:
- IdColumn: Name der ID-Spalte (oder $null)
- TimestampColumn: Name der Timestamp-Spalte (oder $null)
- HasId: Boolean ob ID-Spalte vorhanden
- HasTimestamp: Boolean ob Timestamp-Spalte vorhanden
- SyncStrategy: "Incremental", "FullMerge" oder "Snapshot"
- IsOverride: Boolean ob Override verwendet wurde
.EXAMPLE
$colConfig = Get-TableColumnConfig -TableName "BKUNDE" -Config $Config -ActualColumns @("ID", "NAME", "GESPEICHERT")
# Returns: @{ IdColumn = "ID"; TimestampColumn = "GESPEICHERT"; HasId = $true; HasTimestamp = $true; SyncStrategy = "Incremental" }
.EXAMPLE
# Mit Override in der Config:
# "TableOverrides": { "LEGACY_ORDERS": { "IdColumn": "ORDER_ID", "TimestampColumn": "CHANGED_AT" } }
$colConfig = Get-TableColumnConfig -TableName "LEGACY_ORDERS" -Config $Config -ActualColumns @("ORDER_ID", "NAME", "CHANGED_AT")
# Returns: @{ IdColumn = "ORDER_ID"; TimestampColumn = "CHANGED_AT"; ... }
#>
function Get-TableColumnConfig {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$TableName,
[Parameter(Mandatory)]
[hashtable]$Config,
[Parameter(Mandatory)]
[string[]]$ActualColumns
)
# Defaults aus Config
$DefaultIdColumn = $Config.IdColumn
$DefaultTimestampColumns = $Config.TimestampColumns
# Override prüfen
$Override = $null
$IsOverride = $false
if ($Config.TableOverrides.ContainsKey($TableName)) {
$Override = $Config.TableOverrides[$TableName]
$IsOverride = $true
}
# ID-Spalte bestimmen
$IdColumn = if ($Override -and $Override.IdColumn) {
$Override.IdColumn
}
else {
$DefaultIdColumn
}
# Timestamp-Spalte bestimmen
$TimestampColumn = $null
if ($Override -and $Override.TimestampColumn) {
# Override hat explizite Timestamp-Spalte
$TimestampColumn = $Override.TimestampColumn
}
else {
# Erste gefundene aus der TimestampColumns-Liste verwenden
foreach ($tsCol in $DefaultTimestampColumns) {
if ($tsCol -in $ActualColumns) {
$TimestampColumn = $tsCol
break
}
}
}
# Prüfen ob Spalten existieren
$HasId = $IdColumn -in $ActualColumns
$HasTimestamp = $null -ne $TimestampColumn -and $TimestampColumn -in $ActualColumns
# Strategie ableiten
$SyncStrategy = "Incremental"
if (-not $HasId) {
$SyncStrategy = "Snapshot"
}
elseif (-not $HasTimestamp) {
$SyncStrategy = "FullMerge"
}
return @{
IdColumn = if ($HasId) { $IdColumn } else { $null }
TimestampColumn = if ($HasTimestamp) { $TimestampColumn } else { $null }
HasId = $HasId
HasTimestamp = $HasTimestamp
SyncStrategy = $SyncStrategy
IsOverride = $IsOverride
}
}
#endregion
#region Security Helpers
<#
.SYNOPSIS
Escaped Strings für die Verwendung in Firebird SQL-Statements.
.DESCRIPTION
Verdoppelt einfache Anführungszeichen, um SQL-Injection und Syntaxfehler zu verhindern.
Gibt bei leerem Input einen leeren String zurück (kein Fehler), um auch optionale Felder zu unterstützen.
#>
function Protect-SqlString {
param([string]$InputString)
if ([string]::IsNullOrEmpty($InputString)) {
return ""
}
# Firebird (und SQL Server) escapen einfache Anführungszeichen durch Verdopplung
return $InputString -replace "'", "''"
}
#endregion
# Exportiere alle Public Functions
Export-ModuleMember -Function @(
# Credentials
'Get-StoredCredential'
'Resolve-FirebirdCredentials'
'Resolve-MSSQLCredentials'
# Configuration
'Get-SQLSyncConfig'
'Get-ConfigValue'
'Get-TableColumnConfig'
# Connection Strings
'New-FirebirdConnectionString'
'New-MSSQLConnectionString'
# Driver
'Initialize-FirebirdDriver'
# Safe Operations
# HINWEIS: Invoke-WithFirebirdConnection und Invoke-WithMSSQLConnection wurden entfernt,
# da $using: in normalen ScriptBlocks nicht funktioniert. Stattdessen direkt
# try/finally mit Close-DatabaseConnection verwenden.
'Close-DatabaseConnection'
# Helpers
'Write-SyncStatus'
'ConvertTo-SqlServerType'
'Protect-SqlString'
)