fix(oracle): calea DMPDIR devine parametru; sqlnet.ora ajunge unde e citit
Gasite la instalarea de productie VADECO (Oracle 21c XE, Windows Server 2019). 1. Pe serverul VADECO procesul Oracle nu poate atinge nicio cale de pe C:, nici macar C:\Windows\Temp, desi ACL-urile sunt corecte si serviciul ruleaza ca NT SERVICE\OracleServiceXE. D: merge cu exact acelasi grant. Calea DMP era insa hardcodata "C:\DMPDIR" in 01, 02, 05, 06 si in biblioteca, deci instalarea nu se putea muta. Acum e parametrul -DmpDir, expus ca /dmpdest: in FAZA1.cmd si FAZA2.cmd si transmis tuturor pasilor. Cel mai perfid era pasul 02: recrea DIRECTORY DMPDIR pe 'C:\DMPDIR' peste valoarea pusa de 01. Chiar cu restul instalarii mutata, SYS.NEWSCHEMA ar fi cautat FIRMANOUA.dmp in alta parte, iar adaugarea unei firme noi ar fi picat peste luni, fara legatura vizibila cu instalarea. 2. New-OracleDirectory compara doar siruri de caractere: verifica ce scrie in dba_directories, nu daca baza chiar poate scrie acolo. Acum face un UTL_FILE round-trip si esueaza pe loc, cu explicatia cauzei. Inainte, directorul inutilizabil trecea drept bun si importul cadea abia in impdp cu ORA-29283, la zeci de linii distanta. Valoarea de retur nici nu era verificata in 01/03/06 - de aici si "True" ratacit in log. 3. Instalarea ROAClient seteaza TNS_ADMIN de masina spre instantclient-ul ei. Serviciul Oracle mosteneste variabilele de masina, deci citea sqlnet.ora de acolo - unde nu exista niciunul - si nu din Oracle Home, unde il scria pasul 01. Compatibilitatea pentru clienti vechi nu se aplica, iar statiile ar fi primit ORA-28040 cu fisierul scris corect, in locul gresit. Pasul 01 scrie acum sqlnet.ora si in TNS_ADMIN cand difera. 4. Pasul 05 lega schemele de DMP-uri cu "^$schema[_\.]", deci schema DANUBE putea primi DANUBE_20200914.dmp - datele altei firme, fara avertisment. Numele exact are acum intaietate, prefixul se accepta doar daca e unic, iar ambiguitatea se raporteaza. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SzF1hf4aFS1tmJWpPMiwGp
This commit is contained in:
3
.gitignore
vendored
3
.gitignore
vendored
@@ -16,3 +16,6 @@ input/
|
|||||||
# Secrets - real cPanel DNS hook config holds an API token (template is committed)
|
# Secrets - real cPanel DNS hook config holds an API token (template is committed)
|
||||||
cpanel-dns.config.json
|
cpanel-dns.config.json
|
||||||
**/cpanel-dns.config.json
|
**/cpanel-dns.config.json
|
||||||
|
|
||||||
|
# Cygwin/Git-Bash crash dumps
|
||||||
|
*.stackdump
|
||||||
|
|||||||
@@ -34,6 +34,11 @@ REM /parolavechi:<parola> parola SYS de pe serverul vechi
|
|||||||
REM /licente:<fisier.sql> licente dintr-un fisier, in loc de retea
|
REM /licente:<fisier.sql> licente dintr-un fisier, in loc de retea
|
||||||
REM /roaupdate:<cale> radacina oglinzii (implicit D:\ROAUPDATE)
|
REM /roaupdate:<cale> radacina oglinzii (implicit D:\ROAUPDATE)
|
||||||
REM /export:<cale> director export (implicit D:\ROA\EXPORT_ORADMP)
|
REM /export:<cale> director export (implicit D:\ROA\EXPORT_ORADMP)
|
||||||
|
REM /dmpdest:<cale> de unde citeste baza DMP-urile (implicit C:\DMPDIR)
|
||||||
|
REM Pe unele masini procesul Oracle nu ajunge la C:\ deloc
|
||||||
|
REM (ORA-29283 la orice cale de pe C:, inclusiv C:\Windows\Temp,
|
||||||
|
REM desi ACL-urile sunt corecte). Atunci pune-l pe discul unde
|
||||||
|
REM e Oracle Home: /dmpdest:D:\DMPDIR
|
||||||
REM /faralicente sari peste pasul 09
|
REM /faralicente sari peste pasul 09
|
||||||
REM /faraiis sari peste pasul 10
|
REM /faraiis sari peste pasul 10
|
||||||
REM /farabackup sari peste pasul 11
|
REM /farabackup sari peste pasul 11
|
||||||
@@ -89,6 +94,7 @@ if /i "!OPT!"=="/parolavechi" set "PAROLAVECHI=!VAL!"
|
|||||||
if /i "!OPT!"=="/licente" set "LICENTEFIS=!VAL!"
|
if /i "!OPT!"=="/licente" set "LICENTEFIS=!VAL!"
|
||||||
if /i "!OPT!"=="/roaupdate" set "ROAUPDATE=!VAL!"
|
if /i "!OPT!"=="/roaupdate" set "ROAUPDATE=!VAL!"
|
||||||
if /i "!OPT!"=="/export" set "EXPORTDIR=!VAL!"
|
if /i "!OPT!"=="/export" set "EXPORTDIR=!VAL!"
|
||||||
|
if /i "!OPT!"=="/dmpdest" set "DMPDEST=!VAL!"
|
||||||
|
|
||||||
shift
|
shift
|
||||||
goto :parsare
|
goto :parsare
|
||||||
@@ -102,6 +108,7 @@ echo.
|
|||||||
echo Kit: %KIT%
|
echo Kit: %KIT%
|
||||||
echo Id client: %IDCLIENT%
|
echo Id client: %IDCLIENT%
|
||||||
echo SMTP: %SMTP%
|
echo SMTP: %SMTP%
|
||||||
|
echo DMP: %DMPDEST%
|
||||||
echo ROAUPDATE: %ROAUPDATE%
|
echo ROAUPDATE: %ROAUPDATE%
|
||||||
echo Export: %EXPORTDIR%
|
echo Export: %EXPORTDIR%
|
||||||
if not "%VECHI%"=="" echo Server vechi: %VECHI% / %SERVICIUVECHI%
|
if not "%VECHI%"=="" echo Server vechi: %VECHI% / %SERVICIUVECHI%
|
||||||
@@ -139,7 +146,7 @@ REM [2/9] 01 - baza si userul
|
|||||||
REM ---------------------------------------------------------------------------
|
REM ---------------------------------------------------------------------------
|
||||||
echo.
|
echo.
|
||||||
echo [2/9] 01-setup-database.ps1
|
echo [2/9] 01-setup-database.ps1
|
||||||
powershell.exe -ExecutionPolicy Bypass -NoProfile -File "%KIT%scripts\01-setup-database.ps1"
|
powershell.exe -ExecutionPolicy Bypass -NoProfile -File "%KIT%scripts\01-setup-database.ps1" -DmpDir "%DMPDEST%"
|
||||||
if errorlevel 1 goto :esec_01
|
if errorlevel 1 goto :esec_01
|
||||||
|
|
||||||
REM ---------------------------------------------------------------------------
|
REM ---------------------------------------------------------------------------
|
||||||
@@ -147,7 +154,7 @@ REM [3/9] 02 - obiectele SYS
|
|||||||
REM ---------------------------------------------------------------------------
|
REM ---------------------------------------------------------------------------
|
||||||
echo.
|
echo.
|
||||||
echo [3/9] 02-create-sys-objects.ps1
|
echo [3/9] 02-create-sys-objects.ps1
|
||||||
powershell.exe -ExecutionPolicy Bypass -NoProfile -File "%KIT%scripts\02-create-sys-objects.ps1"
|
powershell.exe -ExecutionPolicy Bypass -NoProfile -File "%KIT%scripts\02-create-sys-objects.ps1" -DmpDir "%DMPDEST%"
|
||||||
if errorlevel 1 goto :esec_02
|
if errorlevel 1 goto :esec_02
|
||||||
|
|
||||||
REM ---------------------------------------------------------------------------
|
REM ---------------------------------------------------------------------------
|
||||||
@@ -155,7 +162,7 @@ REM [4/9] 03 - CONTAFIN_ORACLE
|
|||||||
REM ---------------------------------------------------------------------------
|
REM ---------------------------------------------------------------------------
|
||||||
echo.
|
echo.
|
||||||
echo [4/9] 03-import-contafin.ps1
|
echo [4/9] 03-import-contafin.ps1
|
||||||
powershell.exe -ExecutionPolicy Bypass -NoProfile -File "%KIT%scripts\03-import-contafin.ps1"
|
powershell.exe -ExecutionPolicy Bypass -NoProfile -File "%KIT%scripts\03-import-contafin.ps1" -DmpDir "%DMPDEST%"
|
||||||
set RC=!ERRORLEVEL!
|
set RC=!ERRORLEVEL!
|
||||||
REM Codul 5 e normal: Data Pump raporteaza "completed with errors" pentru
|
REM Codul 5 e normal: Data Pump raporteaza "completed with errors" pentru
|
||||||
REM ORA-31684 (userul e creat deja de pasul 01) si ORA-39082 (warning-uri de
|
REM ORA-31684 (userul e creat deja de pasul 01) si ORA-39082 (warning-uri de
|
||||||
|
|||||||
@@ -28,6 +28,8 @@ REM /smtp:<server> server SMTP (implicit mail.romfast.ro)
|
|||||||
REM /roaupdate:<cale> radacina oglinzii (implicit D:\ROAUPDATE)
|
REM /roaupdate:<cale> radacina oglinzii (implicit D:\ROAUPDATE)
|
||||||
REM /export:<cale> director export (implicit D:\ROA\EXPORT_ORADMP)
|
REM /export:<cale> director export (implicit D:\ROA\EXPORT_ORADMP)
|
||||||
REM /dmp:<cale> de unde se copiaza DMP-urile (implicit <kit>\DMPDIR)
|
REM /dmp:<cale> de unde se copiaza DMP-urile (implicit <kit>\DMPDIR)
|
||||||
|
REM /dmpdest:<cale> de unde le citeste baza (implicit C:\DMPDIR)
|
||||||
|
REM Trebuie sa fie aceeasi valoare ca la FAZA1.
|
||||||
REM /faraschema nu regenera schema.txt
|
REM /faraschema nu regenera schema.txt
|
||||||
REM
|
REM
|
||||||
REM Exemple:
|
REM Exemple:
|
||||||
@@ -72,6 +74,7 @@ if /i "!OPT!"=="/smtp" set "SMTP=!VAL!"
|
|||||||
if /i "!OPT!"=="/roaupdate" set "ROAUPDATE=!VAL!"
|
if /i "!OPT!"=="/roaupdate" set "ROAUPDATE=!VAL!"
|
||||||
if /i "!OPT!"=="/export" set "EXPORTDIR=!VAL!"
|
if /i "!OPT!"=="/export" set "EXPORTDIR=!VAL!"
|
||||||
if /i "!OPT!"=="/dmp" set "DMPSURSA=!VAL!"
|
if /i "!OPT!"=="/dmp" set "DMPSURSA=!VAL!"
|
||||||
|
if /i "!OPT!"=="/dmpdest" set "DMPDEST=!VAL!"
|
||||||
|
|
||||||
shift
|
shift
|
||||||
goto :parsare
|
goto :parsare
|
||||||
@@ -150,12 +153,12 @@ if errorlevel 1 goto :esec_drop
|
|||||||
|
|
||||||
echo.
|
echo.
|
||||||
echo 01-setup-database.ps1 (recreare user)
|
echo 01-setup-database.ps1 (recreare user)
|
||||||
powershell.exe -ExecutionPolicy Bypass -NoProfile -File "%KIT%scripts\01-setup-database.ps1"
|
powershell.exe -ExecutionPolicy Bypass -NoProfile -File "%KIT%scripts\01-setup-database.ps1" -DmpDir "%DMPDEST%"
|
||||||
if errorlevel 1 goto :esec_01
|
if errorlevel 1 goto :esec_01
|
||||||
|
|
||||||
echo.
|
echo.
|
||||||
echo 03-import-contafin.ps1
|
echo 03-import-contafin.ps1
|
||||||
powershell.exe -ExecutionPolicy Bypass -NoProfile -File "%KIT%scripts\03-import-contafin.ps1"
|
powershell.exe -ExecutionPolicy Bypass -NoProfile -File "%KIT%scripts\03-import-contafin.ps1" -DmpDir "%DMPDEST%"
|
||||||
set RC=!ERRORLEVEL!
|
set RC=!ERRORLEVEL!
|
||||||
if "!RC!"=="0" goto :dupa_03
|
if "!RC!"=="0" goto :dupa_03
|
||||||
if "!RC!"=="5" (
|
if "!RC!"=="5" (
|
||||||
@@ -177,7 +180,7 @@ REM [3/6] Schemele de firma
|
|||||||
REM ---------------------------------------------------------------------------
|
REM ---------------------------------------------------------------------------
|
||||||
echo.
|
echo.
|
||||||
echo [3/6] 05-import-companies.ps1
|
echo [3/6] 05-import-companies.ps1
|
||||||
powershell.exe -ExecutionPolicy Bypass -NoProfile -File "%KIT%scripts\05-import-companies.ps1"
|
powershell.exe -ExecutionPolicy Bypass -NoProfile -File "%KIT%scripts\05-import-companies.ps1" -DumpDirectory "%DMPDEST%" -DmpDir "%DMPDEST%"
|
||||||
if errorlevel 1 goto :esec_05
|
if errorlevel 1 goto :esec_05
|
||||||
|
|
||||||
REM ---------------------------------------------------------------------------
|
REM ---------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -87,7 +87,13 @@ param(
|
|||||||
[switch]$SkipSqlnetConfig,
|
[switch]$SkipSqlnetConfig,
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[switch]$ResetSystemPassword
|
[switch]$ResetSystemPassword,
|
||||||
|
|
||||||
|
# Calea fizica a directorului Oracle DMPDIR. Aceeasi valoare trebuie data
|
||||||
|
# tuturor pasilor care ating DMPDIR (01, 02, 03, 05, 06), altfel ultimul
|
||||||
|
# care ruleaza repozitioneaza obiectul si ceilalti citesc din alta parte.
|
||||||
|
[Parameter(Mandatory = $false)]
|
||||||
|
[string]$DmpDir = "C:\DMPDIR"
|
||||||
)
|
)
|
||||||
|
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
@@ -355,6 +361,31 @@ NAMES.DIRECTORY_PATH = (TNSNAMES, EZCONNECT)
|
|||||||
Write-LogSuccess "sqlnet.ora configured at $sqlnetOra"
|
Write-LogSuccess "sqlnet.ora configured at $sqlnetOra"
|
||||||
Write-Log "Old client compatibility enabled (SQLNET.ALLOWED_LOGON_VERSION=8)"
|
Write-Log "Old client compatibility enabled (SQLNET.ALLOWED_LOGON_VERSION=8)"
|
||||||
|
|
||||||
|
# Daca exista TNS_ADMIN la nivel de masina, ACELA castiga - si pentru
|
||||||
|
# clienti, si pentru serviciul Oracle, care mosteneste variabilele de
|
||||||
|
# masina. Instalarea ROAClient il pune sa arate spre instantclient-ul
|
||||||
|
# ei (D:\ROA\instantclient_11_2_0_2), unde de obicei nu exista niciun
|
||||||
|
# sqlnet.ora: atunci serverul cade pe valorile implicite, adica
|
||||||
|
# ALLOWED_LOGON_VERSION_SERVER=12, si clientii vechi primesc ORA-28040
|
||||||
|
# desi fisierul de mai sus a fost scris corect. Scriem acelasi continut
|
||||||
|
# si acolo, altfel toata configurarea de compatibilitate e degeaba.
|
||||||
|
$tnsAdmin = [Environment]::GetEnvironmentVariable('TNS_ADMIN', 'Machine')
|
||||||
|
if ($tnsAdmin) {
|
||||||
|
$tnsAdminFull = [IO.Path]::GetFullPath($tnsAdmin.TrimEnd('\'))
|
||||||
|
if ($tnsAdminFull -ne [IO.Path]::GetFullPath($networkAdmin.TrimEnd('\'))) {
|
||||||
|
Write-LogWarning "TNS_ADMIN de masina arata spre $tnsAdminFull - acolo se citeste sqlnet.ora, nu din Oracle Home."
|
||||||
|
if (-not (Test-Path $tnsAdminFull)) {
|
||||||
|
New-Item -ItemType Directory -Path $tnsAdminFull -Force | Out-Null
|
||||||
|
}
|
||||||
|
$tnsSqlnet = Join-Path $tnsAdminFull "sqlnet.ora"
|
||||||
|
if (Test-Path $tnsSqlnet) {
|
||||||
|
Copy-Item $tnsSqlnet "$tnsSqlnet.bak_$(Get-Date -Format 'yyyyMMdd_HHmmss')" -Force
|
||||||
|
}
|
||||||
|
Set-Content -Path $tnsSqlnet -Value $sqlnetContent -Encoding ASCII
|
||||||
|
Write-LogSuccess "sqlnet.ora scris si in TNS_ADMIN: $tnsSqlnet"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
# Restart listener to apply changes
|
# Restart listener to apply changes
|
||||||
Write-Log "Restarting listener to apply sqlnet.ora changes..."
|
Write-Log "Restarting listener to apply sqlnet.ora changes..."
|
||||||
$lsnrctl = Join-Path $oraHome "bin\lsnrctl.exe"
|
$lsnrctl = Join-Path $oraHome "bin\lsnrctl.exe"
|
||||||
@@ -536,11 +567,12 @@ EXIT;
|
|||||||
# Step 9: Create DMPDIR directory for Data Pump
|
# Step 9: Create DMPDIR directory for Data Pump
|
||||||
Write-LogSection "Creating Data Pump Directory"
|
Write-LogSection "Creating Data Pump Directory"
|
||||||
|
|
||||||
$dmpDir = "C:\DMPDIR"
|
if (-not (New-OracleDirectory -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
New-OracleDirectory -OracleHome $oraHome -ServiceName $ServiceName `
|
-Password $SystemPassword -DirectoryName "DMPDIR" -DirectoryPath $DmpDir)) {
|
||||||
-Password $SystemPassword -DirectoryName "DMPDIR" -DirectoryPath $dmpDir
|
throw "Directorul Data Pump DMPDIR ($DmpDir) nu e utilizabil de catre baza. Vezi mesajele de mai sus."
|
||||||
|
}
|
||||||
|
|
||||||
Write-LogSuccess "Data Pump directory DMPDIR created: $dmpDir"
|
Write-LogSuccess "Data Pump directory DMPDIR created: $DmpDir"
|
||||||
|
|
||||||
# Step 10: Reset passwords with 10G verifier (required for old client auth)
|
# Step 10: Reset passwords with 10G verifier (required for old client auth)
|
||||||
# After sqlnet.ora is configured, passwords must be reset to generate 10G hash
|
# After sqlnet.ora is configured, passwords must be reset to generate 10G hash
|
||||||
|
|||||||
@@ -1,432 +1,438 @@
|
|||||||
#Requires -Version 5.1
|
#Requires -Version 5.1
|
||||||
|
|
||||||
<#
|
<#
|
||||||
.SYNOPSIS
|
.SYNOPSIS
|
||||||
Install SYS objects for ROA Oracle.
|
Install SYS objects for ROA Oracle.
|
||||||
|
|
||||||
.DESCRIPTION
|
.DESCRIPTION
|
||||||
Executes SQL scripts to create required SYS-owned objects including:
|
Executes SQL scripts to create required SYS-owned objects including:
|
||||||
- AUTH_PACK package
|
- AUTH_PACK package
|
||||||
- AUTH_DETALII, AUTH_SERII tables
|
- AUTH_DETALII, AUTH_SERII tables
|
||||||
- NEWSCHEMA, NEWSCHEMAPOST procedures
|
- NEWSCHEMA, NEWSCHEMAPOST procedures
|
||||||
- NEWSCHEMAPROGRESS function
|
- NEWSCHEMAPROGRESS function
|
||||||
- PACK_UPDATE, PACK_UTILS packages
|
- PACK_UPDATE, PACK_UTILS packages
|
||||||
- Public synonyms and grants
|
- Public synonyms and grants
|
||||||
|
|
||||||
.PARAMETER OracleHome
|
.PARAMETER OracleHome
|
||||||
Oracle home directory. If not specified, auto-detects.
|
Oracle home directory. If not specified, auto-detects.
|
||||||
|
|
||||||
.PARAMETER ServiceName
|
.PARAMETER ServiceName
|
||||||
Database service name. Default: XEPDB1
|
Database service name. Default: XEPDB1
|
||||||
|
|
||||||
.PARAMETER SystemPassword
|
.PARAMETER SystemPassword
|
||||||
SYSTEM/SYS user password. Default: romfastsoft
|
SYSTEM/SYS user password. Default: romfastsoft
|
||||||
|
|
||||||
.PARAMETER SqlScriptsDir
|
.PARAMETER SqlScriptsDir
|
||||||
Directory containing SYS SQL scripts. Default: ..\sql
|
Directory containing SYS SQL scripts. Default: ..\sql
|
||||||
|
|
||||||
.EXAMPLE
|
.EXAMPLE
|
||||||
.\02-create-sys-objects.ps1
|
.\02-create-sys-objects.ps1
|
||||||
|
|
||||||
.EXAMPLE
|
.EXAMPLE
|
||||||
.\02-create-sys-objects.ps1 -ServiceName "ROA" -SystemPassword "mypassword"
|
.\02-create-sys-objects.ps1 -ServiceName "ROA" -SystemPassword "mypassword"
|
||||||
|
|
||||||
.NOTES
|
.NOTES
|
||||||
File Name : 02-create-sys-objects.ps1
|
File Name : 02-create-sys-objects.ps1
|
||||||
Prerequisite : Run 01-setup-database.ps1 first
|
Prerequisite : Run 01-setup-database.ps1 first
|
||||||
Copyright 2024 : ROMFAST
|
Copyright 2024 : ROMFAST
|
||||||
#>
|
#>
|
||||||
|
|
||||||
[CmdletBinding()]
|
[CmdletBinding()]
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[string]$OracleHome,
|
[string]$OracleHome,
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[string]$ServiceName = "XEPDB1",
|
[string]$ServiceName = "XEPDB1",
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[string]$SystemPassword = "romfastsoft",
|
[string]$SystemPassword = "romfastsoft",
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[string]$SqlScriptsDir
|
[string]$SqlScriptsDir,
|
||||||
)
|
|
||||||
|
# Calea fizica pe care o primeste obiectul Oracle DIRECTORY DMPDIR.
|
||||||
$ErrorActionPreference = 'Stop'
|
# Trebuie sa fie aceeasi in toti pasii, altfel unul dintre ei repozitioneaza
|
||||||
|
# tacut directorul si SYS.NEWSCHEMA nu-si mai gaseste FIRMANOUA.dmp.
|
||||||
# Source library functions
|
[Parameter(Mandatory = $false)]
|
||||||
. "$PSScriptRoot\lib\logging-functions.ps1"
|
[string]$DmpDir = "C:\DMPDIR"
|
||||||
. "$PSScriptRoot\lib\oracle-functions.ps1"
|
)
|
||||||
|
|
||||||
# Initialize logging
|
$ErrorActionPreference = 'Stop'
|
||||||
$logPath = Join-Path $PSScriptRoot "..\logs\02-create-sys-objects_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
|
|
||||||
Initialize-LogFile -LogPath $logPath -ScriptName "02-create-sys-objects.ps1"
|
# Source library functions
|
||||||
|
. "$PSScriptRoot\lib\logging-functions.ps1"
|
||||||
try {
|
. "$PSScriptRoot\lib\oracle-functions.ps1"
|
||||||
Write-LogSection "Installing SYS Objects"
|
|
||||||
|
# Initialize logging
|
||||||
# Validate Oracle installation
|
$logPath = Join-Path $PSScriptRoot "..\logs\02-create-sys-objects_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
|
||||||
$oraHome = Get-OracleHome -OracleHome $OracleHome
|
Initialize-LogFile -LogPath $logPath -ScriptName "02-create-sys-objects.ps1"
|
||||||
Write-LogSuccess "Oracle Home: $oraHome"
|
|
||||||
|
try {
|
||||||
# Test connection
|
Write-LogSection "Installing SYS Objects"
|
||||||
Write-Log "Testing database connection..."
|
|
||||||
if (-not (Test-OracleConnection -OracleHome $oraHome -ServiceName $ServiceName `
|
# Validate Oracle installation
|
||||||
-Username "SYS" -Password $SystemPassword -AsSysdba)) {
|
$oraHome = Get-OracleHome -OracleHome $OracleHome
|
||||||
throw "Cannot connect to database as SYS. Please verify ServiceName and SystemPassword."
|
Write-LogSuccess "Oracle Home: $oraHome"
|
||||||
}
|
|
||||||
Write-LogSuccess "Database connection successful"
|
# Test connection
|
||||||
|
Write-Log "Testing database connection..."
|
||||||
# Determine SQL scripts directory
|
if (-not (Test-OracleConnection -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
if (-not $SqlScriptsDir) {
|
-Username "SYS" -Password $SystemPassword -AsSysdba)) {
|
||||||
$SqlScriptsDir = Join-Path $PSScriptRoot "..\sql"
|
throw "Cannot connect to database as SYS. Please verify ServiceName and SystemPassword."
|
||||||
}
|
}
|
||||||
|
Write-LogSuccess "Database connection successful"
|
||||||
$sysObjectsScript = Join-Path $SqlScriptsDir "sys-objects.sql"
|
|
||||||
|
# Determine SQL scripts directory
|
||||||
if (-not (Test-Path -Path $sysObjectsScript)) {
|
if (-not $SqlScriptsDir) {
|
||||||
Write-LogWarning "sys-objects.sql not found at $sysObjectsScript"
|
$SqlScriptsDir = Join-Path $PSScriptRoot "..\sql"
|
||||||
Write-Log "Creating sys-objects.sql from embedded SQL..."
|
}
|
||||||
|
|
||||||
# Create the sql directory if it doesn't exist
|
$sysObjectsScript = Join-Path $SqlScriptsDir "sys-objects.sql"
|
||||||
if (-not (Test-Path -Path $SqlScriptsDir)) {
|
|
||||||
New-Item -ItemType Directory -Path $SqlScriptsDir -Force | Out-Null
|
if (-not (Test-Path -Path $sysObjectsScript)) {
|
||||||
}
|
Write-LogWarning "sys-objects.sql not found at $sysObjectsScript"
|
||||||
|
Write-Log "Creating sys-objects.sql from embedded SQL..."
|
||||||
# Embedded SYS objects SQL - minimal set for ROA
|
|
||||||
$sysObjectsSql = @"
|
# Create the sql directory if it doesn't exist
|
||||||
-- sys-objects.sql
|
if (-not (Test-Path -Path $SqlScriptsDir)) {
|
||||||
-- SYS objects required for ROA Oracle
|
New-Item -ItemType Directory -Path $SqlScriptsDir -Force | Out-Null
|
||||||
-- Run as SYS with SYSDBA privilege
|
}
|
||||||
|
|
||||||
SET ECHO ON FEEDBACK ON VERIFY OFF SERVEROUTPUT ON
|
# Embedded SYS objects SQL - minimal set for ROA
|
||||||
|
$sysObjectsSql = @"
|
||||||
PROMPT
|
-- sys-objects.sql
|
||||||
PROMPT =============================================
|
-- SYS objects required for ROA Oracle
|
||||||
PROMPT Creating SYS objects for ROA
|
-- Run as SYS with SYSDBA privilege
|
||||||
PROMPT =============================================
|
|
||||||
PROMPT
|
SET ECHO ON FEEDBACK ON VERIFY OFF SERVEROUTPUT ON
|
||||||
|
|
||||||
-- Create DMPDIR if not exists
|
PROMPT
|
||||||
PROMPT Creating directory DMPDIR...
|
PROMPT =============================================
|
||||||
CREATE OR REPLACE DIRECTORY DMPDIR AS 'C:\DMPDIR';
|
PROMPT Creating SYS objects for ROA
|
||||||
GRANT READ, WRITE ON DIRECTORY DMPDIR TO PUBLIC;
|
PROMPT =============================================
|
||||||
|
PROMPT
|
||||||
-- AUTH_DETALII table
|
|
||||||
PROMPT Creating table AUTH_DETALII...
|
-- Create DMPDIR if not exists
|
||||||
BEGIN
|
PROMPT Creating directory DMPDIR...
|
||||||
EXECUTE IMMEDIATE 'DROP TABLE SYS.AUTH_DETALII CASCADE CONSTRAINTS';
|
CREATE OR REPLACE DIRECTORY DMPDIR AS '$DmpDir';
|
||||||
EXCEPTION WHEN OTHERS THEN NULL;
|
GRANT READ, WRITE ON DIRECTORY DMPDIR TO PUBLIC;
|
||||||
END;
|
|
||||||
/
|
-- AUTH_DETALII table
|
||||||
|
PROMPT Creating table AUTH_DETALII...
|
||||||
CREATE TABLE SYS.AUTH_DETALII (
|
BEGIN
|
||||||
ID_DETALIU NUMBER NOT NULL,
|
EXECUTE IMMEDIATE 'DROP TABLE SYS.AUTH_DETALII CASCADE CONSTRAINTS';
|
||||||
ID_PROGRAM NUMBER NOT NULL,
|
EXCEPTION WHEN OTHERS THEN NULL;
|
||||||
CAMP_DETALIU VARCHAR2(100),
|
END;
|
||||||
VAL_DETALIU VARCHAR2(500),
|
/
|
||||||
CONSTRAINT PK_AUTH_DETALII PRIMARY KEY (ID_DETALIU)
|
|
||||||
);
|
CREATE TABLE SYS.AUTH_DETALII (
|
||||||
|
ID_DETALIU NUMBER NOT NULL,
|
||||||
GRANT SELECT, INSERT, UPDATE, DELETE ON SYS.AUTH_DETALII TO PUBLIC;
|
ID_PROGRAM NUMBER NOT NULL,
|
||||||
CREATE PUBLIC SYNONYM AUTH_DETALII FOR SYS.AUTH_DETALII;
|
CAMP_DETALIU VARCHAR2(100),
|
||||||
|
VAL_DETALIU VARCHAR2(500),
|
||||||
-- AUTH_SERII table
|
CONSTRAINT PK_AUTH_DETALII PRIMARY KEY (ID_DETALIU)
|
||||||
PROMPT Creating table AUTH_SERII...
|
);
|
||||||
BEGIN
|
|
||||||
EXECUTE IMMEDIATE 'DROP TABLE SYS.AUTH_SERII CASCADE CONSTRAINTS';
|
GRANT SELECT, INSERT, UPDATE, DELETE ON SYS.AUTH_DETALII TO PUBLIC;
|
||||||
EXCEPTION WHEN OTHERS THEN NULL;
|
CREATE PUBLIC SYNONYM AUTH_DETALII FOR SYS.AUTH_DETALII;
|
||||||
END;
|
|
||||||
/
|
-- AUTH_SERII table
|
||||||
|
PROMPT Creating table AUTH_SERII...
|
||||||
CREATE TABLE SYS.AUTH_SERII (
|
BEGIN
|
||||||
ID_PROGRAM NUMBER NOT NULL,
|
EXECUTE IMMEDIATE 'DROP TABLE SYS.AUTH_SERII CASCADE CONSTRAINTS';
|
||||||
SERIE VARCHAR2(50),
|
EXCEPTION WHEN OTHERS THEN NULL;
|
||||||
NR_UTIL NUMBER,
|
END;
|
||||||
DATA_VAL DATE,
|
/
|
||||||
CONSTRAINT PK_AUTH_SERII PRIMARY KEY (ID_PROGRAM)
|
|
||||||
);
|
CREATE TABLE SYS.AUTH_SERII (
|
||||||
|
ID_PROGRAM NUMBER NOT NULL,
|
||||||
GRANT SELECT, INSERT, UPDATE, DELETE ON SYS.AUTH_SERII TO PUBLIC;
|
SERIE VARCHAR2(50),
|
||||||
CREATE PUBLIC SYNONYM AUTH_SERII FOR SYS.AUTH_SERII;
|
NR_UTIL NUMBER,
|
||||||
|
DATA_VAL DATE,
|
||||||
-- AUTH_PACK package specification
|
CONSTRAINT PK_AUTH_SERII PRIMARY KEY (ID_PROGRAM)
|
||||||
PROMPT Creating package AUTH_PACK...
|
);
|
||||||
CREATE OR REPLACE PACKAGE SYS.AUTH_PACK AS
|
|
||||||
FUNCTION selecteaza_serie(p_id_program NUMBER) RETURN VARCHAR2;
|
GRANT SELECT, INSERT, UPDATE, DELETE ON SYS.AUTH_SERII TO PUBLIC;
|
||||||
FUNCTION selecteaza_nr_util(p_id_program NUMBER) RETURN NUMBER;
|
CREATE PUBLIC SYNONYM AUTH_SERII FOR SYS.AUTH_SERII;
|
||||||
FUNCTION selecteaza_data_val(p_id_program NUMBER) RETURN DATE;
|
|
||||||
PROCEDURE actualizeaza_serie(p_id_program NUMBER, p_serie VARCHAR2, p_nr_util NUMBER, p_data_val DATE);
|
-- AUTH_PACK package specification
|
||||||
END AUTH_PACK;
|
PROMPT Creating package AUTH_PACK...
|
||||||
/
|
CREATE OR REPLACE PACKAGE SYS.AUTH_PACK AS
|
||||||
|
FUNCTION selecteaza_serie(p_id_program NUMBER) RETURN VARCHAR2;
|
||||||
-- AUTH_PACK package body
|
FUNCTION selecteaza_nr_util(p_id_program NUMBER) RETURN NUMBER;
|
||||||
CREATE OR REPLACE PACKAGE BODY SYS.AUTH_PACK AS
|
FUNCTION selecteaza_data_val(p_id_program NUMBER) RETURN DATE;
|
||||||
|
PROCEDURE actualizeaza_serie(p_id_program NUMBER, p_serie VARCHAR2, p_nr_util NUMBER, p_data_val DATE);
|
||||||
FUNCTION selecteaza_serie(p_id_program NUMBER) RETURN VARCHAR2 IS
|
END AUTH_PACK;
|
||||||
v_serie VARCHAR2(50);
|
/
|
||||||
BEGIN
|
|
||||||
SELECT serie INTO v_serie FROM SYS.AUTH_SERII WHERE id_program = p_id_program;
|
-- AUTH_PACK package body
|
||||||
RETURN v_serie;
|
CREATE OR REPLACE PACKAGE BODY SYS.AUTH_PACK AS
|
||||||
EXCEPTION
|
|
||||||
WHEN NO_DATA_FOUND THEN RETURN NULL;
|
FUNCTION selecteaza_serie(p_id_program NUMBER) RETURN VARCHAR2 IS
|
||||||
END;
|
v_serie VARCHAR2(50);
|
||||||
|
BEGIN
|
||||||
FUNCTION selecteaza_nr_util(p_id_program NUMBER) RETURN NUMBER IS
|
SELECT serie INTO v_serie FROM SYS.AUTH_SERII WHERE id_program = p_id_program;
|
||||||
v_nr_util NUMBER;
|
RETURN v_serie;
|
||||||
BEGIN
|
EXCEPTION
|
||||||
SELECT nr_util INTO v_nr_util FROM SYS.AUTH_SERII WHERE id_program = p_id_program;
|
WHEN NO_DATA_FOUND THEN RETURN NULL;
|
||||||
RETURN v_nr_util;
|
END;
|
||||||
EXCEPTION
|
|
||||||
WHEN NO_DATA_FOUND THEN RETURN NULL;
|
FUNCTION selecteaza_nr_util(p_id_program NUMBER) RETURN NUMBER IS
|
||||||
END;
|
v_nr_util NUMBER;
|
||||||
|
BEGIN
|
||||||
FUNCTION selecteaza_data_val(p_id_program NUMBER) RETURN DATE IS
|
SELECT nr_util INTO v_nr_util FROM SYS.AUTH_SERII WHERE id_program = p_id_program;
|
||||||
v_data_val DATE;
|
RETURN v_nr_util;
|
||||||
BEGIN
|
EXCEPTION
|
||||||
SELECT data_val INTO v_data_val FROM SYS.AUTH_SERII WHERE id_program = p_id_program;
|
WHEN NO_DATA_FOUND THEN RETURN NULL;
|
||||||
RETURN v_data_val;
|
END;
|
||||||
EXCEPTION
|
|
||||||
WHEN NO_DATA_FOUND THEN RETURN NULL;
|
FUNCTION selecteaza_data_val(p_id_program NUMBER) RETURN DATE IS
|
||||||
END;
|
v_data_val DATE;
|
||||||
|
BEGIN
|
||||||
PROCEDURE actualizeaza_serie(p_id_program NUMBER, p_serie VARCHAR2, p_nr_util NUMBER, p_data_val DATE) IS
|
SELECT data_val INTO v_data_val FROM SYS.AUTH_SERII WHERE id_program = p_id_program;
|
||||||
BEGIN
|
RETURN v_data_val;
|
||||||
MERGE INTO SYS.AUTH_SERII t
|
EXCEPTION
|
||||||
USING (SELECT p_id_program AS id_program FROM dual) s
|
WHEN NO_DATA_FOUND THEN RETURN NULL;
|
||||||
ON (t.id_program = s.id_program)
|
END;
|
||||||
WHEN MATCHED THEN
|
|
||||||
UPDATE SET serie = p_serie, nr_util = p_nr_util, data_val = p_data_val
|
PROCEDURE actualizeaza_serie(p_id_program NUMBER, p_serie VARCHAR2, p_nr_util NUMBER, p_data_val DATE) IS
|
||||||
WHEN NOT MATCHED THEN
|
BEGIN
|
||||||
INSERT (id_program, serie, nr_util, data_val)
|
MERGE INTO SYS.AUTH_SERII t
|
||||||
VALUES (p_id_program, p_serie, p_nr_util, p_data_val);
|
USING (SELECT p_id_program AS id_program FROM dual) s
|
||||||
COMMIT;
|
ON (t.id_program = s.id_program)
|
||||||
END;
|
WHEN MATCHED THEN
|
||||||
|
UPDATE SET serie = p_serie, nr_util = p_nr_util, data_val = p_data_val
|
||||||
END AUTH_PACK;
|
WHEN NOT MATCHED THEN
|
||||||
/
|
INSERT (id_program, serie, nr_util, data_val)
|
||||||
|
VALUES (p_id_program, p_serie, p_nr_util, p_data_val);
|
||||||
GRANT EXECUTE ON SYS.AUTH_PACK TO PUBLIC;
|
COMMIT;
|
||||||
CREATE OR REPLACE PUBLIC SYNONYM AUTH_PACK FOR SYS.AUTH_PACK;
|
END;
|
||||||
|
|
||||||
-- VAUTH_SERII view
|
END AUTH_PACK;
|
||||||
PROMPT Creating view VAUTH_SERII...
|
/
|
||||||
CREATE OR REPLACE VIEW SYS.VAUTH_SERII AS
|
|
||||||
SELECT a.id_program,
|
GRANT EXECUTE ON SYS.AUTH_PACK TO PUBLIC;
|
||||||
a.denumire AS nume,
|
CREATE OR REPLACE PUBLIC SYNONYM AUTH_PACK FOR SYS.AUTH_PACK;
|
||||||
auth_pack.selecteaza_serie(a.id_program) AS serie,
|
|
||||||
auth_pack.selecteaza_nr_util(a.id_program) AS nr_util,
|
-- VAUTH_SERII view
|
||||||
auth_pack.selecteaza_data_val(a.id_program) AS data_val
|
PROMPT Creating view VAUTH_SERII...
|
||||||
FROM syn_nom_programe a
|
CREATE OR REPLACE VIEW SYS.VAUTH_SERII AS
|
||||||
LEFT JOIN syn_def_programe b ON a.id_program = b.ide_program
|
SELECT a.id_program,
|
||||||
WHERE b.sters = 0
|
a.denumire AS nume,
|
||||||
AND b.instalat = 1;
|
auth_pack.selecteaza_serie(a.id_program) AS serie,
|
||||||
|
auth_pack.selecteaza_nr_util(a.id_program) AS nr_util,
|
||||||
GRANT SELECT ON SYS.VAUTH_SERII TO PUBLIC;
|
auth_pack.selecteaza_data_val(a.id_program) AS data_val
|
||||||
CREATE OR REPLACE PUBLIC SYNONYM VAUTH_SERII FOR SYS.VAUTH_SERII;
|
FROM syn_nom_programe a
|
||||||
|
LEFT JOIN syn_def_programe b ON a.id_program = b.ide_program
|
||||||
-- PACK_UPDATE package (minimal version)
|
WHERE b.sters = 0
|
||||||
PROMPT Creating package PACK_UPDATE...
|
AND b.instalat = 1;
|
||||||
CREATE OR REPLACE PACKAGE SYS.PACK_UPDATE AS
|
|
||||||
FUNCTION get_version RETURN VARCHAR2;
|
GRANT SELECT ON SYS.VAUTH_SERII TO PUBLIC;
|
||||||
PROCEDURE execute_sql(p_sql VARCHAR2);
|
CREATE OR REPLACE PUBLIC SYNONYM VAUTH_SERII FOR SYS.VAUTH_SERII;
|
||||||
END PACK_UPDATE;
|
|
||||||
/
|
-- PACK_UPDATE package (minimal version)
|
||||||
|
PROMPT Creating package PACK_UPDATE...
|
||||||
CREATE OR REPLACE PACKAGE BODY SYS.PACK_UPDATE AS
|
CREATE OR REPLACE PACKAGE SYS.PACK_UPDATE AS
|
||||||
|
FUNCTION get_version RETURN VARCHAR2;
|
||||||
FUNCTION get_version RETURN VARCHAR2 IS
|
PROCEDURE execute_sql(p_sql VARCHAR2);
|
||||||
BEGIN
|
END PACK_UPDATE;
|
||||||
RETURN '1.0.0';
|
/
|
||||||
END;
|
|
||||||
|
CREATE OR REPLACE PACKAGE BODY SYS.PACK_UPDATE AS
|
||||||
PROCEDURE execute_sql(p_sql VARCHAR2) IS
|
|
||||||
BEGIN
|
FUNCTION get_version RETURN VARCHAR2 IS
|
||||||
EXECUTE IMMEDIATE p_sql;
|
BEGIN
|
||||||
EXCEPTION
|
RETURN '1.0.0';
|
||||||
WHEN OTHERS THEN
|
END;
|
||||||
RAISE;
|
|
||||||
END;
|
PROCEDURE execute_sql(p_sql VARCHAR2) IS
|
||||||
|
BEGIN
|
||||||
END PACK_UPDATE;
|
EXECUTE IMMEDIATE p_sql;
|
||||||
/
|
EXCEPTION
|
||||||
|
WHEN OTHERS THEN
|
||||||
GRANT EXECUTE ON SYS.PACK_UPDATE TO PUBLIC;
|
RAISE;
|
||||||
CREATE OR REPLACE PUBLIC SYNONYM PACK_UPDATE FOR SYS.PACK_UPDATE;
|
END;
|
||||||
|
|
||||||
-- PACK_UTILS package (minimal version)
|
END PACK_UPDATE;
|
||||||
PROMPT Creating package PACK_UTILS...
|
/
|
||||||
CREATE OR REPLACE PACKAGE SYS.PACK_UTILS AS
|
|
||||||
FUNCTION get_db_version RETURN VARCHAR2;
|
GRANT EXECUTE ON SYS.PACK_UPDATE TO PUBLIC;
|
||||||
FUNCTION get_instance_name RETURN VARCHAR2;
|
CREATE OR REPLACE PUBLIC SYNONYM PACK_UPDATE FOR SYS.PACK_UPDATE;
|
||||||
END PACK_UTILS;
|
|
||||||
/
|
-- PACK_UTILS package (minimal version)
|
||||||
|
PROMPT Creating package PACK_UTILS...
|
||||||
CREATE OR REPLACE PACKAGE BODY SYS.PACK_UTILS AS
|
CREATE OR REPLACE PACKAGE SYS.PACK_UTILS AS
|
||||||
|
FUNCTION get_db_version RETURN VARCHAR2;
|
||||||
FUNCTION get_db_version RETURN VARCHAR2 IS
|
FUNCTION get_instance_name RETURN VARCHAR2;
|
||||||
v_version VARCHAR2(100);
|
END PACK_UTILS;
|
||||||
BEGIN
|
/
|
||||||
SELECT version_full INTO v_version FROM v`$instance;
|
|
||||||
RETURN v_version;
|
CREATE OR REPLACE PACKAGE BODY SYS.PACK_UTILS AS
|
||||||
EXCEPTION
|
|
||||||
WHEN OTHERS THEN RETURN NULL;
|
FUNCTION get_db_version RETURN VARCHAR2 IS
|
||||||
END;
|
v_version VARCHAR2(100);
|
||||||
|
BEGIN
|
||||||
FUNCTION get_instance_name RETURN VARCHAR2 IS
|
SELECT version_full INTO v_version FROM v`$instance;
|
||||||
v_instance VARCHAR2(100);
|
RETURN v_version;
|
||||||
BEGIN
|
EXCEPTION
|
||||||
SELECT instance_name INTO v_instance FROM v`$instance;
|
WHEN OTHERS THEN RETURN NULL;
|
||||||
RETURN v_instance;
|
END;
|
||||||
EXCEPTION
|
|
||||||
WHEN OTHERS THEN RETURN NULL;
|
FUNCTION get_instance_name RETURN VARCHAR2 IS
|
||||||
END;
|
v_instance VARCHAR2(100);
|
||||||
|
BEGIN
|
||||||
END PACK_UTILS;
|
SELECT instance_name INTO v_instance FROM v`$instance;
|
||||||
/
|
RETURN v_instance;
|
||||||
|
EXCEPTION
|
||||||
GRANT EXECUTE ON SYS.PACK_UTILS TO PUBLIC;
|
WHEN OTHERS THEN RETURN NULL;
|
||||||
CREATE OR REPLACE PUBLIC SYNONYM PACK_UTILS FOR SYS.PACK_UTILS;
|
END;
|
||||||
|
|
||||||
-- Grant UTL packages to PUBLIC
|
END PACK_UTILS;
|
||||||
PROMPT Granting UTL packages...
|
/
|
||||||
GRANT EXECUTE ON UTL_FILE TO PUBLIC;
|
|
||||||
GRANT EXECUTE ON DBMS_LOCK TO PUBLIC;
|
GRANT EXECUTE ON SYS.PACK_UTILS TO PUBLIC;
|
||||||
|
CREATE OR REPLACE PUBLIC SYNONYM PACK_UTILS FOR SYS.PACK_UTILS;
|
||||||
-- Grant UTL packages to CONTAFIN_ORACLE specifically
|
|
||||||
GRANT EXECUTE ON UTL_INADDR TO CONTAFIN_ORACLE;
|
-- Grant UTL packages to PUBLIC
|
||||||
GRANT EXECUTE ON UTL_TCP TO CONTAFIN_ORACLE;
|
PROMPT Granting UTL packages...
|
||||||
GRANT EXECUTE ON UTL_SMTP TO CONTAFIN_ORACLE;
|
GRANT EXECUTE ON UTL_FILE TO PUBLIC;
|
||||||
GRANT EXECUTE ON UTL_HTTP TO CONTAFIN_ORACLE;
|
GRANT EXECUTE ON DBMS_LOCK TO PUBLIC;
|
||||||
|
|
||||||
COMMIT;
|
-- Grant UTL packages to CONTAFIN_ORACLE specifically
|
||||||
|
GRANT EXECUTE ON UTL_INADDR TO CONTAFIN_ORACLE;
|
||||||
PROMPT
|
GRANT EXECUTE ON UTL_TCP TO CONTAFIN_ORACLE;
|
||||||
PROMPT =============================================
|
GRANT EXECUTE ON UTL_SMTP TO CONTAFIN_ORACLE;
|
||||||
PROMPT SYS objects created successfully
|
GRANT EXECUTE ON UTL_HTTP TO CONTAFIN_ORACLE;
|
||||||
PROMPT =============================================
|
|
||||||
PROMPT
|
COMMIT;
|
||||||
|
|
||||||
SELECT 'SYS_OBJECTS_COMPLETE' FROM dual;
|
PROMPT
|
||||||
|
PROMPT =============================================
|
||||||
EXIT;
|
PROMPT SYS objects created successfully
|
||||||
"@
|
PROMPT =============================================
|
||||||
|
PROMPT
|
||||||
Set-Content -Path $sysObjectsScript -Value $sysObjectsSql -Encoding ASCII
|
|
||||||
Write-Log "Created sys-objects.sql"
|
SELECT 'SYS_OBJECTS_COMPLETE' FROM dual;
|
||||||
}
|
|
||||||
|
EXIT;
|
||||||
# Execute SYS objects script
|
"@
|
||||||
Write-LogSection "Executing sys-objects.sql"
|
|
||||||
|
Set-Content -Path $sysObjectsScript -Value $sysObjectsSql -Encoding ASCII
|
||||||
$result = Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
Write-Log "Created sys-objects.sql"
|
||||||
-Username "SYS" -Password $SystemPassword -SqlFile $sysObjectsScript -AsSysdba
|
}
|
||||||
|
|
||||||
if ($result -match "SYS_OBJECTS_COMPLETE") {
|
# Execute SYS objects script
|
||||||
Write-LogSuccess "SYS objects created successfully"
|
Write-LogSection "Executing sys-objects.sql"
|
||||||
}
|
|
||||||
else {
|
$result = Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
Write-LogWarning "Script completed but could not verify success"
|
-Username "SYS" -Password $SystemPassword -SqlFile $sysObjectsScript -AsSysdba
|
||||||
Write-LogDebug $result
|
|
||||||
}
|
if ($result -match "SYS_OBJECTS_COMPLETE") {
|
||||||
|
Write-LogSuccess "SYS objects created successfully"
|
||||||
# Verify created objects
|
}
|
||||||
Write-LogSection "Verifying SYS Objects"
|
else {
|
||||||
|
Write-LogWarning "Script completed but could not verify success"
|
||||||
$verifySql = @"
|
Write-LogDebug $result
|
||||||
SET PAGESIZE 100 FEEDBACK OFF VERIFY OFF HEADING ON ECHO OFF LINESIZE 200
|
}
|
||||||
|
|
||||||
PROMPT
|
# Verify created objects
|
||||||
PROMPT === SYS Objects Status ===
|
Write-LogSection "Verifying SYS Objects"
|
||||||
PROMPT
|
|
||||||
|
$verifySql = @"
|
||||||
SELECT object_name, object_type, status
|
SET PAGESIZE 100 FEEDBACK OFF VERIFY OFF HEADING ON ECHO OFF LINESIZE 200
|
||||||
FROM dba_objects
|
|
||||||
WHERE owner = 'SYS'
|
PROMPT
|
||||||
AND object_name IN ('AUTH_PACK', 'AUTH_DETALII', 'AUTH_SERII', 'VAUTH_SERII',
|
PROMPT === SYS Objects Status ===
|
||||||
'PACK_UPDATE', 'PACK_UTILS', 'NEWSCHEMA', 'NEWSCHEMAPOST', 'NEWSCHEMAPROGRESS')
|
PROMPT
|
||||||
ORDER BY object_type, object_name;
|
|
||||||
|
SELECT object_name, object_type, status
|
||||||
PROMPT
|
FROM dba_objects
|
||||||
PROMPT === Public Synonyms ===
|
WHERE owner = 'SYS'
|
||||||
PROMPT
|
AND object_name IN ('AUTH_PACK', 'AUTH_DETALII', 'AUTH_SERII', 'VAUTH_SERII',
|
||||||
|
'PACK_UPDATE', 'PACK_UTILS', 'NEWSCHEMA', 'NEWSCHEMAPOST', 'NEWSCHEMAPROGRESS')
|
||||||
SELECT synonym_name, table_owner, table_name
|
ORDER BY object_type, object_name;
|
||||||
FROM dba_synonyms
|
|
||||||
WHERE owner = 'PUBLIC'
|
PROMPT
|
||||||
AND table_name IN ('AUTH_PACK', 'AUTH_DETALII', 'AUTH_SERII', 'VAUTH_SERII',
|
PROMPT === Public Synonyms ===
|
||||||
'PACK_UPDATE', 'PACK_UTILS', 'NEWSCHEMA', 'NEWSCHEMAPOST', 'NEWSCHEMAPROGRESS')
|
PROMPT
|
||||||
ORDER BY synonym_name;
|
|
||||||
|
SELECT synonym_name, table_owner, table_name
|
||||||
EXIT;
|
FROM dba_synonyms
|
||||||
"@
|
WHERE owner = 'PUBLIC'
|
||||||
|
AND table_name IN ('AUTH_PACK', 'AUTH_DETALII', 'AUTH_SERII', 'VAUTH_SERII',
|
||||||
$verifyResult = Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
'PACK_UPDATE', 'PACK_UTILS', 'NEWSCHEMA', 'NEWSCHEMAPOST', 'NEWSCHEMAPROGRESS')
|
||||||
-Username "SYS" -Password $SystemPassword -SqlCommand $verifySql -AsSysdba
|
ORDER BY synonym_name;
|
||||||
|
|
||||||
Write-Host $verifyResult
|
EXIT;
|
||||||
|
"@
|
||||||
# Count invalid objects
|
|
||||||
$invalidSql = @"
|
$verifyResult = Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
SET PAGESIZE 0 FEEDBACK OFF VERIFY OFF HEADING OFF ECHO OFF
|
-Username "SYS" -Password $SystemPassword -SqlCommand $verifySql -AsSysdba
|
||||||
SELECT 'INVALID_COUNT:' || COUNT(*)
|
|
||||||
FROM dba_objects
|
Write-Host $verifyResult
|
||||||
WHERE owner = 'SYS'
|
|
||||||
AND object_name IN ('AUTH_PACK', 'AUTH_DETALII', 'AUTH_SERII', 'VAUTH_SERII',
|
# Count invalid objects
|
||||||
'PACK_UPDATE', 'PACK_UTILS', 'NEWSCHEMA', 'NEWSCHEMAPOST', 'NEWSCHEMAPROGRESS')
|
$invalidSql = @"
|
||||||
AND status = 'INVALID';
|
SET PAGESIZE 0 FEEDBACK OFF VERIFY OFF HEADING OFF ECHO OFF
|
||||||
EXIT;
|
SELECT 'INVALID_COUNT:' || COUNT(*)
|
||||||
"@
|
FROM dba_objects
|
||||||
|
WHERE owner = 'SYS'
|
||||||
$invalidResult = Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
AND object_name IN ('AUTH_PACK', 'AUTH_DETALII', 'AUTH_SERII', 'VAUTH_SERII',
|
||||||
-Username "SYS" -Password $SystemPassword -SqlCommand $invalidSql -AsSysdba -Silent
|
'PACK_UPDATE', 'PACK_UTILS', 'NEWSCHEMA', 'NEWSCHEMAPOST', 'NEWSCHEMAPROGRESS')
|
||||||
|
AND status = 'INVALID';
|
||||||
$invalidCount = 0
|
EXIT;
|
||||||
if ($invalidResult -match "INVALID_COUNT:(\d+)") {
|
"@
|
||||||
$invalidCount = [int]$Matches[1]
|
|
||||||
}
|
$invalidResult = Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
|
-Username "SYS" -Password $SystemPassword -SqlCommand $invalidSql -AsSysdba -Silent
|
||||||
if ($invalidCount -gt 0) {
|
|
||||||
Write-LogWarning "$invalidCount invalid SYS objects found"
|
$invalidCount = 0
|
||||||
Write-Log "Attempting to recompile invalid objects..."
|
if ($invalidResult -match "INVALID_COUNT:(\d+)") {
|
||||||
|
$invalidCount = [int]$Matches[1]
|
||||||
$recompileSql = @"
|
}
|
||||||
SET SERVEROUTPUT ON
|
|
||||||
BEGIN
|
if ($invalidCount -gt 0) {
|
||||||
DBMS_UTILITY.COMPILE_SCHEMA('SYS', FALSE);
|
Write-LogWarning "$invalidCount invalid SYS objects found"
|
||||||
END;
|
Write-Log "Attempting to recompile invalid objects..."
|
||||||
/
|
|
||||||
EXIT;
|
$recompileSql = @"
|
||||||
"@
|
SET SERVEROUTPUT ON
|
||||||
Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
BEGIN
|
||||||
-Username "SYS" -Password $SystemPassword -SqlCommand $recompileSql -AsSysdba -Silent
|
DBMS_UTILITY.COMPILE_SCHEMA('SYS', FALSE);
|
||||||
}
|
END;
|
||||||
else {
|
/
|
||||||
Write-LogSuccess "All SYS objects are valid"
|
EXIT;
|
||||||
}
|
"@
|
||||||
|
Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
# Summary
|
-Username "SYS" -Password $SystemPassword -SqlCommand $recompileSql -AsSysdba -Silent
|
||||||
Write-LogSection "Setup Complete"
|
}
|
||||||
Write-LogSuccess "SYS objects installation completed!"
|
else {
|
||||||
Write-Log ""
|
Write-LogSuccess "All SYS objects are valid"
|
||||||
Write-Log "Objects created:"
|
}
|
||||||
Write-Log " - AUTH_PACK package"
|
|
||||||
Write-Log " - AUTH_DETALII table"
|
# Summary
|
||||||
Write-Log " - AUTH_SERII table"
|
Write-LogSection "Setup Complete"
|
||||||
Write-Log " - VAUTH_SERII view"
|
Write-LogSuccess "SYS objects installation completed!"
|
||||||
Write-Log " - PACK_UPDATE package"
|
Write-Log ""
|
||||||
Write-Log " - PACK_UTILS package"
|
Write-Log "Objects created:"
|
||||||
Write-Log " - Public synonyms and grants"
|
Write-Log " - AUTH_PACK package"
|
||||||
Write-Log ""
|
Write-Log " - AUTH_DETALII table"
|
||||||
Write-Log "Next steps:"
|
Write-Log " - AUTH_SERII table"
|
||||||
Write-Log " 1. Run 03-import-contafin.ps1 to import CONTAFIN_ORACLE schema"
|
Write-Log " - VAUTH_SERII view"
|
||||||
|
Write-Log " - PACK_UPDATE package"
|
||||||
Close-LogFile -Success $true
|
Write-Log " - PACK_UTILS package"
|
||||||
exit 0
|
Write-Log " - Public synonyms and grants"
|
||||||
}
|
Write-Log ""
|
||||||
catch {
|
Write-Log "Next steps:"
|
||||||
Write-LogError "Setup failed: $_"
|
Write-Log " 1. Run 03-import-contafin.ps1 to import CONTAFIN_ORACLE schema"
|
||||||
Write-LogError $_.ScriptStackTrace
|
|
||||||
Close-LogFile -Success $false
|
Close-LogFile -Success $true
|
||||||
exit 1
|
exit 0
|
||||||
}
|
}
|
||||||
|
catch {
|
||||||
|
Write-LogError "Setup failed: $_"
|
||||||
|
Write-LogError $_.ScriptStackTrace
|
||||||
|
Close-LogFile -Success $false
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,334 +1,339 @@
|
|||||||
#Requires -Version 5.1
|
#Requires -Version 5.1
|
||||||
|
|
||||||
<#
|
<#
|
||||||
.SYNOPSIS
|
.SYNOPSIS
|
||||||
Import CONTAFIN_ORACLE schema from Data Pump dump file.
|
Import CONTAFIN_ORACLE schema from Data Pump dump file.
|
||||||
|
|
||||||
.DESCRIPTION
|
.DESCRIPTION
|
||||||
Imports the CONTAFIN_ORACLE schema using Oracle Data Pump (impdp).
|
Imports the CONTAFIN_ORACLE schema using Oracle Data Pump (impdp).
|
||||||
- Creates DMPDIR directory if not exists
|
- Creates DMPDIR directory if not exists
|
||||||
- Runs impdp with optimal parameters
|
- Runs impdp with optimal parameters
|
||||||
- Verifies import (object count, invalid objects)
|
- Verifies import (object count, invalid objects)
|
||||||
|
|
||||||
.PARAMETER DumpFile
|
.PARAMETER DumpFile
|
||||||
Path to the CONTAFIN_ORACLE DMP file. If not specified, auto-detects from DmpDir.
|
Path to the CONTAFIN_ORACLE DMP file. If not specified, auto-detects from DmpDir.
|
||||||
|
|
||||||
.PARAMETER OracleHome
|
.PARAMETER OracleHome
|
||||||
Oracle home directory. If not specified, auto-detects.
|
Oracle home directory. If not specified, auto-detects.
|
||||||
|
|
||||||
.PARAMETER ServiceName
|
.PARAMETER ServiceName
|
||||||
Database service name. Default: XEPDB1
|
Database service name. Default: XEPDB1
|
||||||
|
|
||||||
.PARAMETER SystemPassword
|
.PARAMETER SystemPassword
|
||||||
SYSTEM user password. Default: romfastsoft
|
SYSTEM user password. Default: romfastsoft
|
||||||
|
|
||||||
.PARAMETER DmpDir
|
.PARAMETER DmpDir
|
||||||
Oracle directory path for Data Pump. Default: C:\DMPDIR
|
Oracle directory path for Data Pump. Default: C:\DMPDIR
|
||||||
|
|
||||||
.PARAMETER TableExistsAction
|
.PARAMETER TableExistsAction
|
||||||
What to do if table exists: SKIP, APPEND, TRUNCATE, REPLACE. Default: REPLACE
|
What to do if table exists: SKIP, APPEND, TRUNCATE, REPLACE. Default: REPLACE
|
||||||
|
|
||||||
.PARAMETER Parallel
|
.PARAMETER Parallel
|
||||||
Number of parallel workers for import. Default: 2
|
Number of parallel workers for import. Default: 2
|
||||||
|
|
||||||
.EXAMPLE
|
.EXAMPLE
|
||||||
.\03-import-contafin.ps1 -DumpFile "C:\dumps\CONTAFIN_ORACLE.dmp"
|
.\03-import-contafin.ps1 -DumpFile "C:\dumps\CONTAFIN_ORACLE.dmp"
|
||||||
|
|
||||||
.EXAMPLE
|
.EXAMPLE
|
||||||
.\03-import-contafin.ps1 -DumpFile "D:\backups\contafin.dmp" -ServiceName "ROA" -SystemPassword "mypass"
|
.\03-import-contafin.ps1 -DumpFile "D:\backups\contafin.dmp" -ServiceName "ROA" -SystemPassword "mypass"
|
||||||
|
|
||||||
.NOTES
|
.NOTES
|
||||||
File Name : 03-import-contafin.ps1
|
File Name : 03-import-contafin.ps1
|
||||||
Prerequisite : Run 01-setup-database.ps1 and 02-create-sys-objects.ps1 first
|
Prerequisite : Run 01-setup-database.ps1 and 02-create-sys-objects.ps1 first
|
||||||
Copyright 2024 : ROMFAST
|
Copyright 2024 : ROMFAST
|
||||||
#>
|
#>
|
||||||
|
|
||||||
[CmdletBinding()]
|
[CmdletBinding()]
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[string]$DumpFile,
|
[string]$DumpFile,
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[string]$OracleHome,
|
[string]$OracleHome,
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[string]$ServiceName = "XEPDB1",
|
[string]$ServiceName = "XEPDB1",
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[string]$SystemPassword = "romfastsoft",
|
[string]$SystemPassword = "romfastsoft",
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[string]$DmpDir = "C:\DMPDIR",
|
[string]$DmpDir = "C:\DMPDIR",
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[ValidateSet('SKIP', 'APPEND', 'TRUNCATE', 'REPLACE')]
|
[ValidateSet('SKIP', 'APPEND', 'TRUNCATE', 'REPLACE')]
|
||||||
[string]$TableExistsAction = "REPLACE",
|
[string]$TableExistsAction = "REPLACE",
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[int]$Parallel = 1
|
[int]$Parallel = 1
|
||||||
)
|
)
|
||||||
|
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
# Source library functions
|
# Source library functions
|
||||||
. "$PSScriptRoot\lib\logging-functions.ps1"
|
. "$PSScriptRoot\lib\logging-functions.ps1"
|
||||||
. "$PSScriptRoot\lib\oracle-functions.ps1"
|
. "$PSScriptRoot\lib\oracle-functions.ps1"
|
||||||
|
|
||||||
# Initialize logging
|
# Initialize logging
|
||||||
$logPath = Join-Path $PSScriptRoot "..\logs\03-import-contafin_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
|
$logPath = Join-Path $PSScriptRoot "..\logs\03-import-contafin_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
|
||||||
Initialize-LogFile -LogPath $logPath -ScriptName "03-import-contafin.ps1"
|
Initialize-LogFile -LogPath $logPath -ScriptName "03-import-contafin.ps1"
|
||||||
|
|
||||||
# Auto-detect DumpFile if not specified
|
# Auto-detect DumpFile if not specified
|
||||||
if (-not $DumpFile) {
|
if (-not $DumpFile) {
|
||||||
Write-Host "[INFO] DumpFile not specified, searching in $DmpDir..." -ForegroundColor Yellow
|
Write-Host "[INFO] DumpFile not specified, searching in $DmpDir..." -ForegroundColor Yellow
|
||||||
$candidates = Get-ChildItem -Path $DmpDir -Filter "*contafin*.dmp" -ErrorAction SilentlyContinue |
|
$candidates = Get-ChildItem -Path $DmpDir -Filter "*contafin*.dmp" -ErrorAction SilentlyContinue |
|
||||||
Sort-Object LastWriteTime -Descending
|
Sort-Object LastWriteTime -Descending
|
||||||
if ($candidates) {
|
if ($candidates) {
|
||||||
$DumpFile = $candidates[0].FullName
|
$DumpFile = $candidates[0].FullName
|
||||||
Write-Host "[INFO] Auto-detected DumpFile: $DumpFile" -ForegroundColor Green
|
Write-Host "[INFO] Auto-detected DumpFile: $DumpFile" -ForegroundColor Green
|
||||||
} else {
|
} else {
|
||||||
throw "No CONTAFIN_ORACLE dump file found in $DmpDir. Please specify -DumpFile parameter or copy *contafin*.dmp to $DmpDir"
|
throw "No CONTAFIN_ORACLE dump file found in $DmpDir. Please specify -DumpFile parameter or copy *contafin*.dmp to $DmpDir"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# Validate DumpFile exists
|
# Validate DumpFile exists
|
||||||
if (-not (Test-Path $DumpFile)) {
|
if (-not (Test-Path $DumpFile)) {
|
||||||
throw "DumpFile not found: $DumpFile"
|
throw "DumpFile not found: $DumpFile"
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Write-LogSection "Importing CONTAFIN_ORACLE Schema"
|
Write-LogSection "Importing CONTAFIN_ORACLE Schema"
|
||||||
|
|
||||||
# Validate Oracle installation
|
# Validate Oracle installation
|
||||||
$oraHome = Get-OracleHome -OracleHome $OracleHome
|
$oraHome = Get-OracleHome -OracleHome $OracleHome
|
||||||
Write-LogSuccess "Oracle Home: $oraHome"
|
Write-LogSuccess "Oracle Home: $oraHome"
|
||||||
|
|
||||||
# Test connection
|
# Test connection
|
||||||
Write-Log "Testing database connection..."
|
Write-Log "Testing database connection..."
|
||||||
if (-not (Test-OracleConnection -OracleHome $oraHome -ServiceName $ServiceName `
|
if (-not (Test-OracleConnection -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
-Password $SystemPassword)) {
|
-Password $SystemPassword)) {
|
||||||
throw "Cannot connect to database. Please verify ServiceName and SystemPassword."
|
throw "Cannot connect to database. Please verify ServiceName and SystemPassword."
|
||||||
}
|
}
|
||||||
Write-LogSuccess "Database connection successful"
|
Write-LogSuccess "Database connection successful"
|
||||||
|
|
||||||
# Verify CONTAFIN_ORACLE user exists
|
# Verify CONTAFIN_ORACLE user exists
|
||||||
Write-Log "Verifying CONTAFIN_ORACLE user exists..."
|
Write-Log "Verifying CONTAFIN_ORACLE user exists..."
|
||||||
if (-not (Test-OracleUser -OracleHome $oraHome -ServiceName $ServiceName `
|
if (-not (Test-OracleUser -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
-Password $SystemPassword -SchemaName "CONTAFIN_ORACLE")) {
|
-Password $SystemPassword -SchemaName "CONTAFIN_ORACLE")) {
|
||||||
throw "User CONTAFIN_ORACLE does not exist. Run 01-setup-database.ps1 first."
|
throw "User CONTAFIN_ORACLE does not exist. Run 01-setup-database.ps1 first."
|
||||||
}
|
}
|
||||||
Write-LogSuccess "User CONTAFIN_ORACLE exists"
|
Write-LogSuccess "User CONTAFIN_ORACLE exists"
|
||||||
|
|
||||||
# Create/verify DMPDIR
|
# Create/verify DMPDIR
|
||||||
Write-LogSection "Configuring Data Pump Directory"
|
Write-LogSection "Configuring Data Pump Directory"
|
||||||
|
|
||||||
if (-not (Test-Path -Path $DmpDir)) {
|
if (-not (Test-Path -Path $DmpDir)) {
|
||||||
New-Item -ItemType Directory -Path $DmpDir -Force | Out-Null
|
New-Item -ItemType Directory -Path $DmpDir -Force | Out-Null
|
||||||
Write-Log "Created directory: $DmpDir"
|
Write-Log "Created directory: $DmpDir"
|
||||||
}
|
}
|
||||||
|
|
||||||
New-OracleDirectory -OracleHome $oraHome -ServiceName $ServiceName `
|
# Valoarea de retur nu era verificata - de aici si "True" ratacit in log.
|
||||||
-Password $SystemPassword -DirectoryName "DMPDIR" -DirectoryPath $DmpDir
|
# Mai rau: cand directorul nu era utilizabil, importul mergea mai departe si
|
||||||
|
# cadea abia in impdp cu ORA-29283, la zeci de linii distanta de cauza.
|
||||||
# Copy dump file to DMPDIR if not already there
|
if (-not (New-OracleDirectory -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
$dumpFileName = Split-Path -Path $DumpFile -Leaf
|
-Password $SystemPassword -DirectoryName "DMPDIR" -DirectoryPath $DmpDir)) {
|
||||||
$targetDumpPath = Join-Path $DmpDir $dumpFileName
|
throw "Directorul Data Pump DMPDIR ($DmpDir) nu e utilizabil de catre baza. Vezi mesajele de mai sus."
|
||||||
|
}
|
||||||
# Resolve paths for accurate comparison (handles casing and path format differences)
|
|
||||||
$resolvedSource = (Resolve-Path -Path $DumpFile -ErrorAction SilentlyContinue).Path
|
# Copy dump file to DMPDIR if not already there
|
||||||
$resolvedTarget = if (Test-Path $targetDumpPath) { (Resolve-Path -Path $targetDumpPath).Path } else { $null }
|
$dumpFileName = Split-Path -Path $DumpFile -Leaf
|
||||||
|
$targetDumpPath = Join-Path $DmpDir $dumpFileName
|
||||||
if ($resolvedSource -ne $resolvedTarget) {
|
|
||||||
Write-Log "Copying dump file to DMPDIR..."
|
# Resolve paths for accurate comparison (handles casing and path format differences)
|
||||||
Copy-Item -Path $DumpFile -Destination $targetDumpPath -Force
|
$resolvedSource = (Resolve-Path -Path $DumpFile -ErrorAction SilentlyContinue).Path
|
||||||
Write-LogSuccess "Dump file copied to: $targetDumpPath"
|
$resolvedTarget = if (Test-Path $targetDumpPath) { (Resolve-Path -Path $targetDumpPath).Path } else { $null }
|
||||||
}
|
|
||||||
else {
|
if ($resolvedSource -ne $resolvedTarget) {
|
||||||
Write-Log "Dump file already in DMPDIR: $targetDumpPath"
|
Write-Log "Copying dump file to DMPDIR..."
|
||||||
}
|
Copy-Item -Path $DumpFile -Destination $targetDumpPath -Force
|
||||||
|
Write-LogSuccess "Dump file copied to: $targetDumpPath"
|
||||||
# Check dump file size
|
}
|
||||||
$dumpFileInfo = Get-Item $targetDumpPath
|
else {
|
||||||
$dumpSizeMB = [math]::Round($dumpFileInfo.Length / 1MB, 2)
|
Write-Log "Dump file already in DMPDIR: $targetDumpPath"
|
||||||
Write-Log "Dump file size: $dumpSizeMB MB"
|
}
|
||||||
|
|
||||||
# Get current object count before import
|
# Check dump file size
|
||||||
Write-Log "Getting current object count for CONTAFIN_ORACLE..."
|
$dumpFileInfo = Get-Item $targetDumpPath
|
||||||
$beforeCounts = Get-SchemaObjectCount -OracleHome $oraHome -ServiceName $ServiceName `
|
$dumpSizeMB = [math]::Round($dumpFileInfo.Length / 1MB, 2)
|
||||||
-Password $SystemPassword -SchemaName "CONTAFIN_ORACLE"
|
Write-Log "Dump file size: $dumpSizeMB MB"
|
||||||
|
|
||||||
$beforeTotal = if ($beforeCounts['TOTAL']) { $beforeCounts['TOTAL'] } else { 0 }
|
# Get current object count before import
|
||||||
Write-Log "Objects before import: $beforeTotal"
|
Write-Log "Getting current object count for CONTAFIN_ORACLE..."
|
||||||
|
$beforeCounts = Get-SchemaObjectCount -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
# Run import
|
-Password $SystemPassword -SchemaName "CONTAFIN_ORACLE"
|
||||||
Write-LogSection "Running Data Pump Import"
|
|
||||||
|
$beforeTotal = if ($beforeCounts['TOTAL']) { $beforeCounts['TOTAL'] } else { 0 }
|
||||||
$impdpPath = Join-Path $oraHome "bin\impdp.exe"
|
Write-Log "Objects before import: $beforeTotal"
|
||||||
if (-not (Test-Path -Path $impdpPath)) {
|
|
||||||
throw "impdp.exe not found at: $impdpPath"
|
# Run import
|
||||||
}
|
Write-LogSection "Running Data Pump Import"
|
||||||
|
|
||||||
$importLogFile = "CONTAFIN_ORACLE_import_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
|
$impdpPath = Join-Path $oraHome "bin\impdp.exe"
|
||||||
|
if (-not (Test-Path -Path $impdpPath)) {
|
||||||
# Get listener host for connection (handles listener bound to specific IP)
|
throw "impdp.exe not found at: $impdpPath"
|
||||||
$dbHost = Get-ListenerHost -OracleHome $oraHome
|
}
|
||||||
$dbPort = 1521
|
|
||||||
|
$importLogFile = "CONTAFIN_ORACLE_import_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
|
||||||
# Build impdp command with EZConnect format
|
|
||||||
$connString = "SYSTEM/`"$SystemPassword`"@${dbHost}:${dbPort}/${ServiceName}"
|
# Get listener host for connection (handles listener bound to specific IP)
|
||||||
|
$dbHost = Get-ListenerHost -OracleHome $oraHome
|
||||||
$impdpParams = @(
|
$dbPort = 1521
|
||||||
"`"$connString`"",
|
|
||||||
"directory=DMPDIR",
|
# Build impdp command with EZConnect format
|
||||||
"dumpfile=$dumpFileName",
|
$connString = "SYSTEM/`"$SystemPassword`"@${dbHost}:${dbPort}/${ServiceName}"
|
||||||
"logfile=$importLogFile",
|
|
||||||
"schemas=CONTAFIN_ORACLE",
|
$impdpParams = @(
|
||||||
"table_exists_action=$TableExistsAction",
|
"`"$connString`"",
|
||||||
"parallel=$Parallel" # Always specify to override DMP metadata (XE requires parallel=1)
|
"directory=DMPDIR",
|
||||||
)
|
"dumpfile=$dumpFileName",
|
||||||
|
"logfile=$importLogFile",
|
||||||
$arguments = $impdpParams -join " "
|
"schemas=CONTAFIN_ORACLE",
|
||||||
|
"table_exists_action=$TableExistsAction",
|
||||||
Write-Log "Executing impdp..."
|
"parallel=$Parallel" # Always specify to override DMP metadata (XE requires parallel=1)
|
||||||
Write-Log "Parameters: directory=DMPDIR dumpfile=$dumpFileName schemas=CONTAFIN_ORACLE table_exists_action=$TableExistsAction"
|
)
|
||||||
|
|
||||||
# Set Oracle environment
|
$arguments = $impdpParams -join " "
|
||||||
$env:ORACLE_HOME = $oraHome
|
|
||||||
$env:PATH = "$oraHome\bin;$env:PATH"
|
Write-Log "Executing impdp..."
|
||||||
$env:NLS_LANG = "AMERICAN_AMERICA.AL32UTF8"
|
Write-Log "Parameters: directory=DMPDIR dumpfile=$dumpFileName schemas=CONTAFIN_ORACLE table_exists_action=$TableExistsAction"
|
||||||
|
|
||||||
$startTime = Get-Date
|
# Set Oracle environment
|
||||||
|
$env:ORACLE_HOME = $oraHome
|
||||||
# Execute impdp
|
$env:PATH = "$oraHome\bin;$env:PATH"
|
||||||
$process = Start-Process -FilePath $impdpPath -ArgumentList $arguments -Wait -NoNewWindow -PassThru
|
$env:NLS_LANG = "AMERICAN_AMERICA.AL32UTF8"
|
||||||
|
|
||||||
$duration = (Get-Date) - $startTime
|
$startTime = Get-Date
|
||||||
Write-Log "Import completed in $([math]::Round($duration.TotalMinutes, 2)) minutes"
|
|
||||||
|
# Execute impdp
|
||||||
# Check import log
|
$process = Start-Process -FilePath $impdpPath -ArgumentList $arguments -Wait -NoNewWindow -PassThru
|
||||||
$importLogPath = Join-Path $DmpDir $importLogFile
|
|
||||||
if (Test-Path -Path $importLogPath) {
|
$duration = (Get-Date) - $startTime
|
||||||
Write-Log "Import log: $importLogPath"
|
Write-Log "Import completed in $([math]::Round($duration.TotalMinutes, 2)) minutes"
|
||||||
|
|
||||||
# Read and analyze log for errors
|
# Check import log
|
||||||
$logContent = Get-Content -Path $importLogPath -Raw
|
$importLogPath = Join-Path $DmpDir $importLogFile
|
||||||
|
if (Test-Path -Path $importLogPath) {
|
||||||
if ($logContent -match "ORA-\d{5}:") {
|
Write-Log "Import log: $importLogPath"
|
||||||
Write-LogWarning "Import completed with Oracle errors. Check log for details."
|
|
||||||
}
|
# Read and analyze log for errors
|
||||||
|
$logContent = Get-Content -Path $importLogPath -Raw
|
||||||
if ($logContent -match "successfully loaded/unloaded") {
|
|
||||||
Write-LogSuccess "Objects successfully loaded"
|
if ($logContent -match "ORA-\d{5}:") {
|
||||||
}
|
Write-LogWarning "Import completed with Oracle errors. Check log for details."
|
||||||
|
}
|
||||||
# Count errors and warnings in log
|
|
||||||
$errorCount = ([regex]::Matches($logContent, "ORA-\d{5}:")).Count
|
if ($logContent -match "successfully loaded/unloaded") {
|
||||||
$warningCount = ([regex]::Matches($logContent, "ORA-39\d{3}:")).Count
|
Write-LogSuccess "Objects successfully loaded"
|
||||||
|
}
|
||||||
Write-Log "Errors in log: $errorCount"
|
|
||||||
Write-Log "Warnings in log: $warningCount"
|
# Count errors and warnings in log
|
||||||
}
|
$errorCount = ([regex]::Matches($logContent, "ORA-\d{5}:")).Count
|
||||||
|
$warningCount = ([regex]::Matches($logContent, "ORA-39\d{3}:")).Count
|
||||||
# Verify import
|
|
||||||
Write-LogSection "Verifying Import"
|
Write-Log "Errors in log: $errorCount"
|
||||||
|
Write-Log "Warnings in log: $warningCount"
|
||||||
# Get object counts after import
|
}
|
||||||
$afterCounts = Get-SchemaObjectCount -OracleHome $oraHome -ServiceName $ServiceName `
|
|
||||||
-Password $SystemPassword -SchemaName "CONTAFIN_ORACLE"
|
# Verify import
|
||||||
|
Write-LogSection "Verifying Import"
|
||||||
$afterTotal = if ($afterCounts['TOTAL']) { $afterCounts['TOTAL'] } else { 0 }
|
|
||||||
$afterInvalid = if ($afterCounts['INVALID']) { $afterCounts['INVALID'] } else { 0 }
|
# Get object counts after import
|
||||||
|
$afterCounts = Get-SchemaObjectCount -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
Write-Log "Objects after import: $afterTotal"
|
-Password $SystemPassword -SchemaName "CONTAFIN_ORACLE"
|
||||||
Write-Log "Objects imported: $($afterTotal - $beforeTotal)"
|
|
||||||
|
$afterTotal = if ($afterCounts['TOTAL']) { $afterCounts['TOTAL'] } else { 0 }
|
||||||
# Display object counts by type
|
$afterInvalid = if ($afterCounts['INVALID']) { $afterCounts['INVALID'] } else { 0 }
|
||||||
Write-Log ""
|
|
||||||
Write-Log "Object counts by type:"
|
Write-Log "Objects after import: $afterTotal"
|
||||||
foreach ($key in $afterCounts.Keys | Sort-Object) {
|
Write-Log "Objects imported: $($afterTotal - $beforeTotal)"
|
||||||
if ($key -ne 'TOTAL' -and $key -ne 'INVALID') {
|
|
||||||
Write-Log " $($key): $($afterCounts[$key])"
|
# Display object counts by type
|
||||||
}
|
Write-Log ""
|
||||||
}
|
Write-Log "Object counts by type:"
|
||||||
|
foreach ($key in $afterCounts.Keys | Sort-Object) {
|
||||||
if ($afterInvalid -gt 0) {
|
if ($key -ne 'TOTAL' -and $key -ne 'INVALID') {
|
||||||
Write-LogWarning "Invalid objects: $afterInvalid"
|
Write-Log " $($key): $($afterCounts[$key])"
|
||||||
|
}
|
||||||
# List invalid objects
|
}
|
||||||
$invalidSql = @"
|
|
||||||
SET PAGESIZE 100 FEEDBACK OFF VERIFY OFF HEADING ON ECHO OFF LINESIZE 200
|
if ($afterInvalid -gt 0) {
|
||||||
SELECT object_name, object_type
|
Write-LogWarning "Invalid objects: $afterInvalid"
|
||||||
FROM dba_objects
|
|
||||||
WHERE owner = 'CONTAFIN_ORACLE'
|
# List invalid objects
|
||||||
AND status = 'INVALID'
|
$invalidSql = @"
|
||||||
ORDER BY object_type, object_name;
|
SET PAGESIZE 100 FEEDBACK OFF VERIFY OFF HEADING ON ECHO OFF LINESIZE 200
|
||||||
EXIT;
|
SELECT object_name, object_type
|
||||||
"@
|
FROM dba_objects
|
||||||
$invalidList = Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
WHERE owner = 'CONTAFIN_ORACLE'
|
||||||
-Username "SYSTEM" -Password $SystemPassword -SqlCommand $invalidSql -Silent
|
AND status = 'INVALID'
|
||||||
|
ORDER BY object_type, object_name;
|
||||||
Write-Log "Invalid objects:"
|
EXIT;
|
||||||
Write-Host $invalidList
|
"@
|
||||||
|
$invalidList = Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
# Attempt to recompile
|
-Username "SYSTEM" -Password $SystemPassword -SqlCommand $invalidSql -Silent
|
||||||
Write-Log "Attempting to recompile invalid objects..."
|
|
||||||
$recompileSql = @"
|
Write-Log "Invalid objects:"
|
||||||
SET SERVEROUTPUT ON
|
Write-Host $invalidList
|
||||||
BEGIN
|
|
||||||
DBMS_UTILITY.COMPILE_SCHEMA('CONTAFIN_ORACLE', FALSE);
|
# Attempt to recompile
|
||||||
END;
|
Write-Log "Attempting to recompile invalid objects..."
|
||||||
/
|
$recompileSql = @"
|
||||||
EXIT;
|
SET SERVEROUTPUT ON
|
||||||
"@
|
BEGIN
|
||||||
Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
DBMS_UTILITY.COMPILE_SCHEMA('CONTAFIN_ORACLE', FALSE);
|
||||||
-Username "SYSTEM" -Password $SystemPassword -SqlCommand $recompileSql -Silent
|
END;
|
||||||
|
/
|
||||||
# Recheck invalid count
|
EXIT;
|
||||||
$recheckCounts = Get-SchemaObjectCount -OracleHome $oraHome -ServiceName $ServiceName `
|
"@
|
||||||
-Password $SystemPassword -SchemaName "CONTAFIN_ORACLE"
|
Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
|
-Username "SYSTEM" -Password $SystemPassword -SqlCommand $recompileSql -Silent
|
||||||
$recheckInvalid = if ($recheckCounts['INVALID']) { $recheckCounts['INVALID'] } else { 0 }
|
|
||||||
|
# Recheck invalid count
|
||||||
if ($recheckInvalid -lt $afterInvalid) {
|
$recheckCounts = Get-SchemaObjectCount -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
Write-LogSuccess "Recompilation fixed $($afterInvalid - $recheckInvalid) objects"
|
-Password $SystemPassword -SchemaName "CONTAFIN_ORACLE"
|
||||||
}
|
|
||||||
|
$recheckInvalid = if ($recheckCounts['INVALID']) { $recheckCounts['INVALID'] } else { 0 }
|
||||||
if ($recheckInvalid -gt 0) {
|
|
||||||
Write-LogWarning "Still $recheckInvalid invalid objects remaining"
|
if ($recheckInvalid -lt $afterInvalid) {
|
||||||
}
|
Write-LogSuccess "Recompilation fixed $($afterInvalid - $recheckInvalid) objects"
|
||||||
}
|
}
|
||||||
else {
|
|
||||||
Write-LogSuccess "No invalid objects"
|
if ($recheckInvalid -gt 0) {
|
||||||
}
|
Write-LogWarning "Still $recheckInvalid invalid objects remaining"
|
||||||
|
}
|
||||||
# Summary
|
}
|
||||||
Write-LogSection "Import Complete"
|
else {
|
||||||
|
Write-LogSuccess "No invalid objects"
|
||||||
if ($process.ExitCode -eq 0) {
|
}
|
||||||
Write-LogSuccess "CONTAFIN_ORACLE schema imported successfully!"
|
|
||||||
}
|
# Summary
|
||||||
else {
|
Write-LogSection "Import Complete"
|
||||||
Write-LogWarning "Import completed with warnings (exit code: $($process.ExitCode))"
|
|
||||||
}
|
if ($process.ExitCode -eq 0) {
|
||||||
|
Write-LogSuccess "CONTAFIN_ORACLE schema imported successfully!"
|
||||||
Write-Log ""
|
}
|
||||||
Write-Log "Summary:"
|
else {
|
||||||
Write-Log " Dump file: $dumpFileName ($dumpSizeMB MB)"
|
Write-LogWarning "Import completed with warnings (exit code: $($process.ExitCode))"
|
||||||
Write-Log " Service: $ServiceName"
|
}
|
||||||
Write-Log " Duration: $([math]::Round($duration.TotalMinutes, 2)) minutes"
|
|
||||||
Write-Log " Objects: $afterTotal"
|
Write-Log ""
|
||||||
Write-Log " Import log: $importLogPath"
|
Write-Log "Summary:"
|
||||||
Write-Log ""
|
Write-Log " Dump file: $dumpFileName ($dumpSizeMB MB)"
|
||||||
Write-Log "Next steps:"
|
Write-Log " Service: $ServiceName"
|
||||||
Write-Log " 1. Run 04-create-synonyms-grants.ps1 to create public synonyms"
|
Write-Log " Duration: $([math]::Round($duration.TotalMinutes, 2)) minutes"
|
||||||
Write-Log " 2. Run 05-import-companies.ps1 to import company schemas"
|
Write-Log " Objects: $afterTotal"
|
||||||
|
Write-Log " Import log: $importLogPath"
|
||||||
Close-LogFile -Success ($process.ExitCode -eq 0)
|
Write-Log ""
|
||||||
exit $process.ExitCode
|
Write-Log "Next steps:"
|
||||||
}
|
Write-Log " 1. Run 04-create-synonyms-grants.ps1 to create public synonyms"
|
||||||
catch {
|
Write-Log " 2. Run 05-import-companies.ps1 to import company schemas"
|
||||||
Write-LogError "Import failed: $_"
|
|
||||||
Write-LogError $_.ScriptStackTrace
|
Close-LogFile -Success ($process.ExitCode -eq 0)
|
||||||
Close-LogFile -Success $false
|
exit $process.ExitCode
|
||||||
exit 1
|
}
|
||||||
}
|
catch {
|
||||||
|
Write-LogError "Import failed: $_"
|
||||||
|
Write-LogError $_.ScriptStackTrace
|
||||||
|
Close-LogFile -Success $false
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,432 +1,448 @@
|
|||||||
#Requires -Version 5.1
|
#Requires -Version 5.1
|
||||||
|
|
||||||
<#
|
<#
|
||||||
.SYNOPSIS
|
.SYNOPSIS
|
||||||
Batch import company schemas from Data Pump dump files.
|
Batch import company schemas from Data Pump dump files.
|
||||||
|
|
||||||
.DESCRIPTION
|
.DESCRIPTION
|
||||||
Imports company schemas from dump files. CRITICAL: Reads passwords from
|
Imports company schemas from dump files. CRITICAL: Reads passwords from
|
||||||
CONTAFIN_ORACLE.NOM_FIRME table to ensure correct authentication.
|
CONTAFIN_ORACLE.NOM_FIRME table to ensure correct authentication.
|
||||||
|
|
||||||
For each company:
|
For each company:
|
||||||
1. Queries NOM_FIRME for schema name and password
|
1. Queries NOM_FIRME for schema name and password
|
||||||
2. Finds matching DMP file in DumpDirectory
|
2. Finds matching DMP file in DumpDirectory
|
||||||
3. Creates user with password from NOM_FIRME
|
3. Creates user with password from NOM_FIRME
|
||||||
4. Runs impdp to import schema
|
4. Runs impdp to import schema
|
||||||
5. Logs progress
|
5. Logs progress
|
||||||
|
|
||||||
.PARAMETER DumpDirectory
|
.PARAMETER DumpDirectory
|
||||||
Directory containing company DMP files. If not specified, defaults to C:\DMPDIR.
|
Directory containing company DMP files. If not specified, defaults to C:\DMPDIR.
|
||||||
|
|
||||||
.PARAMETER OracleHome
|
.PARAMETER OracleHome
|
||||||
Oracle home directory. If not specified, auto-detects.
|
Oracle home directory. If not specified, auto-detects.
|
||||||
|
|
||||||
.PARAMETER ServiceName
|
.PARAMETER ServiceName
|
||||||
Database service name. Default: XEPDB1
|
Database service name. Default: XEPDB1
|
||||||
|
|
||||||
.PARAMETER SystemPassword
|
.PARAMETER SystemPassword
|
||||||
SYSTEM user password. Default: romfastsoft
|
SYSTEM user password. Default: romfastsoft
|
||||||
|
|
||||||
.PARAMETER ParallelJobs
|
.PARAMETER ParallelJobs
|
||||||
Number of parallel import jobs. Default: 2
|
Number of parallel import jobs. Default: 2
|
||||||
|
|
||||||
.PARAMETER Companies
|
.PARAMETER Companies
|
||||||
Optional array of specific company names to import. If not specified, imports all.
|
Optional array of specific company names to import. If not specified, imports all.
|
||||||
|
|
||||||
.PARAMETER DryRun
|
.PARAMETER DryRun
|
||||||
Show what would be imported without actually importing.
|
Show what would be imported without actually importing.
|
||||||
|
|
||||||
.EXAMPLE
|
.EXAMPLE
|
||||||
.\05-import-companies.ps1 -DumpDirectory "C:\dumps\companies"
|
.\05-import-companies.ps1 -DumpDirectory "C:\dumps\companies"
|
||||||
|
|
||||||
.EXAMPLE
|
.EXAMPLE
|
||||||
.\05-import-companies.ps1 -DumpDirectory "D:\backups" -Companies "FIRMA1","FIRMA2"
|
.\05-import-companies.ps1 -DumpDirectory "D:\backups" -Companies "FIRMA1","FIRMA2"
|
||||||
|
|
||||||
.EXAMPLE
|
.EXAMPLE
|
||||||
.\05-import-companies.ps1 -DumpDirectory "C:\dumps" -DryRun
|
.\05-import-companies.ps1 -DumpDirectory "C:\dumps" -DryRun
|
||||||
|
|
||||||
.NOTES
|
.NOTES
|
||||||
File Name : 05-import-companies.ps1
|
File Name : 05-import-companies.ps1
|
||||||
Prerequisite : Run 04-create-synonyms-grants.ps1 first
|
Prerequisite : Run 04-create-synonyms-grants.ps1 first
|
||||||
Copyright 2024 : ROMFAST
|
Copyright 2024 : ROMFAST
|
||||||
#>
|
#>
|
||||||
|
|
||||||
[CmdletBinding()]
|
[CmdletBinding()]
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[string]$DumpDirectory = "C:\DMPDIR",
|
[string]$DumpDirectory = "C:\DMPDIR",
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
# Calea fizica a directorului Oracle DMPDIR - de acolo citeste baza.
|
||||||
[string]$OracleHome,
|
# Implicit e aceeasi cu DumpDirectory, deci nu trebuie data decat cand
|
||||||
|
# DMP-urile stau in alta parte decat directorul pe care il vede baza.
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[string]$ServiceName = "XEPDB1",
|
[string]$DmpDir,
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[string]$SystemPassword = "romfastsoft",
|
[string]$OracleHome,
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[int]$ParallelJobs = 2,
|
[string]$ServiceName = "XEPDB1",
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[string[]]$Companies,
|
[string]$SystemPassword = "romfastsoft",
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[switch]$DryRun
|
[int]$ParallelJobs = 2,
|
||||||
)
|
|
||||||
|
[Parameter(Mandatory = $false)]
|
||||||
$ErrorActionPreference = 'Stop'
|
[string[]]$Companies,
|
||||||
|
|
||||||
# Source library functions
|
[Parameter(Mandatory = $false)]
|
||||||
. "$PSScriptRoot\lib\logging-functions.ps1"
|
[switch]$DryRun
|
||||||
. "$PSScriptRoot\lib\oracle-functions.ps1"
|
)
|
||||||
|
|
||||||
# Initialize logging
|
$ErrorActionPreference = 'Stop'
|
||||||
$logPath = Join-Path $PSScriptRoot "..\logs\05-import-companies_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
|
|
||||||
Initialize-LogFile -LogPath $logPath -ScriptName "05-import-companies.ps1"
|
# Source library functions
|
||||||
|
. "$PSScriptRoot\lib\logging-functions.ps1"
|
||||||
try {
|
. "$PSScriptRoot\lib\oracle-functions.ps1"
|
||||||
Write-LogSection "Batch Import Company Schemas"
|
|
||||||
|
# Initialize logging
|
||||||
# Validate DumpDirectory exists
|
$logPath = Join-Path $PSScriptRoot "..\logs\05-import-companies_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
|
||||||
if (-not (Test-Path $DumpDirectory -PathType Container)) {
|
Initialize-LogFile -LogPath $logPath -ScriptName "05-import-companies.ps1"
|
||||||
throw "DumpDirectory not found: $DumpDirectory"
|
|
||||||
}
|
try {
|
||||||
Write-Log "Using dump directory: $DumpDirectory"
|
Write-LogSection "Batch Import Company Schemas"
|
||||||
|
|
||||||
if ($DryRun) {
|
# Validate DumpDirectory exists
|
||||||
Write-LogWarning "DRY RUN MODE - No changes will be made"
|
if (-not (Test-Path $DumpDirectory -PathType Container)) {
|
||||||
}
|
throw "DumpDirectory not found: $DumpDirectory"
|
||||||
|
}
|
||||||
# Validate Oracle installation
|
Write-Log "Using dump directory: $DumpDirectory"
|
||||||
$oraHome = Get-OracleHome -OracleHome $OracleHome
|
|
||||||
Write-LogSuccess "Oracle Home: $oraHome"
|
if ($DryRun) {
|
||||||
|
Write-LogWarning "DRY RUN MODE - No changes will be made"
|
||||||
# Test connection
|
}
|
||||||
Write-Log "Testing database connection..."
|
|
||||||
if (-not (Test-OracleConnection -OracleHome $oraHome -ServiceName $ServiceName `
|
# Validate Oracle installation
|
||||||
-Password $SystemPassword)) {
|
$oraHome = Get-OracleHome -OracleHome $OracleHome
|
||||||
throw "Cannot connect to database. Please verify ServiceName and SystemPassword."
|
Write-LogSuccess "Oracle Home: $oraHome"
|
||||||
}
|
|
||||||
Write-LogSuccess "Database connection successful"
|
# Test connection
|
||||||
|
Write-Log "Testing database connection..."
|
||||||
# Get company list from NOM_FIRME
|
if (-not (Test-OracleConnection -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
Write-LogSection "Reading Company List from NOM_FIRME"
|
-Password $SystemPassword)) {
|
||||||
|
throw "Cannot connect to database. Please verify ServiceName and SystemPassword."
|
||||||
$companySql = @"
|
}
|
||||||
SET PAGESIZE 10000 FEEDBACK OFF VERIFY OFF HEADING OFF ECHO OFF LINESIZE 500
|
Write-LogSuccess "Database connection successful"
|
||||||
SELECT schema || '|' || parola
|
|
||||||
FROM CONTAFIN_ORACLE.NOM_FIRME
|
# Get company list from NOM_FIRME
|
||||||
WHERE sters = 0
|
Write-LogSection "Reading Company List from NOM_FIRME"
|
||||||
AND schema IS NOT NULL
|
|
||||||
ORDER BY schema;
|
$companySql = @"
|
||||||
EXIT;
|
SET PAGESIZE 10000 FEEDBACK OFF VERIFY OFF HEADING OFF ECHO OFF LINESIZE 500
|
||||||
"@
|
SELECT schema || '|' || parola
|
||||||
|
FROM CONTAFIN_ORACLE.NOM_FIRME
|
||||||
$companyResult = Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
WHERE sters = 0
|
||||||
-Username "SYSTEM" -Password $SystemPassword -SqlCommand $companySql -Silent
|
AND schema IS NOT NULL
|
||||||
|
ORDER BY schema;
|
||||||
# Parse company data
|
EXIT;
|
||||||
$companyData = @{}
|
"@
|
||||||
foreach ($line in $companyResult -split "`n") {
|
|
||||||
$line = $line.Trim()
|
$companyResult = Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
if ($line -match "^([A-Z0-9_]+)\|(.*)$") {
|
-Username "SYSTEM" -Password $SystemPassword -SqlCommand $companySql -Silent
|
||||||
$schema = $Matches[1]
|
|
||||||
$password = $Matches[2]
|
# Parse company data
|
||||||
if (-not $password) { $password = "ROMFASTSOFT" }
|
$companyData = @{}
|
||||||
$companyData[$schema] = $password
|
foreach ($line in $companyResult -split "`n") {
|
||||||
}
|
$line = $line.Trim()
|
||||||
}
|
if ($line -match "^([A-Z0-9_]+)\|(.*)$") {
|
||||||
|
$schema = $Matches[1]
|
||||||
Write-Log "Found $($companyData.Count) companies in NOM_FIRME"
|
$password = $Matches[2]
|
||||||
|
if (-not $password) { $password = "ROMFASTSOFT" }
|
||||||
if ($companyData.Count -eq 0) {
|
$companyData[$schema] = $password
|
||||||
Write-LogWarning "No companies found in NOM_FIRME"
|
}
|
||||||
Close-LogFile -Success $true
|
}
|
||||||
exit 0
|
|
||||||
}
|
Write-Log "Found $($companyData.Count) companies in NOM_FIRME"
|
||||||
|
|
||||||
# Filter companies if specified
|
if ($companyData.Count -eq 0) {
|
||||||
if ($Companies) {
|
Write-LogWarning "No companies found in NOM_FIRME"
|
||||||
$filteredData = @{}
|
Close-LogFile -Success $true
|
||||||
foreach ($company in $Companies) {
|
exit 0
|
||||||
$companyUpper = $company.ToUpper()
|
}
|
||||||
if ($companyData.ContainsKey($companyUpper)) {
|
|
||||||
$filteredData[$companyUpper] = $companyData[$companyUpper]
|
# Filter companies if specified
|
||||||
}
|
if ($Companies) {
|
||||||
else {
|
$filteredData = @{}
|
||||||
Write-LogWarning "Company $companyUpper not found in NOM_FIRME"
|
foreach ($company in $Companies) {
|
||||||
}
|
$companyUpper = $company.ToUpper()
|
||||||
}
|
if ($companyData.ContainsKey($companyUpper)) {
|
||||||
$companyData = $filteredData
|
$filteredData[$companyUpper] = $companyData[$companyUpper]
|
||||||
Write-Log "Filtered to $($companyData.Count) companies"
|
}
|
||||||
}
|
else {
|
||||||
|
Write-LogWarning "Company $companyUpper not found in NOM_FIRME"
|
||||||
# Find matching dump files
|
}
|
||||||
Write-LogSection "Scanning Dump Files"
|
}
|
||||||
|
$companyData = $filteredData
|
||||||
$dumpFiles = Get-ChildItem -Path $DumpDirectory -Filter "*.dmp" -File
|
Write-Log "Filtered to $($companyData.Count) companies"
|
||||||
Write-Log "Found $($dumpFiles.Count) DMP files in $DumpDirectory"
|
}
|
||||||
|
|
||||||
# Match companies with dump files
|
# Find matching dump files
|
||||||
$importList = @()
|
Write-LogSection "Scanning Dump Files"
|
||||||
$notFoundList = @()
|
|
||||||
|
$dumpFiles = Get-ChildItem -Path $DumpDirectory -Filter "*.dmp" -File
|
||||||
foreach ($schema in $companyData.Keys) {
|
Write-Log "Found $($dumpFiles.Count) DMP files in $DumpDirectory"
|
||||||
# Try to find matching dump file (case-insensitive)
|
|
||||||
$matchingFile = $dumpFiles | Where-Object {
|
# Match companies with dump files
|
||||||
$_.BaseName -ieq $schema -or
|
$importList = @()
|
||||||
$_.BaseName -imatch "^$schema[_\.]" -or
|
$notFoundList = @()
|
||||||
$_.BaseName -imatch "^${schema}$"
|
|
||||||
} | Select-Object -First 1
|
foreach ($schema in $companyData.Keys) {
|
||||||
|
# Numele exact are intaietate. Fara asta, schema DANUBE putea primi
|
||||||
if ($matchingFile) {
|
# DANUBE_20200914.dmp - datele altei firme, fara niciun avertisment.
|
||||||
$importList += [PSCustomObject]@{
|
$matchingFile = $dumpFiles | Where-Object { $_.BaseName -ieq $schema } | Select-Object -First 1
|
||||||
Schema = $schema
|
|
||||||
Password = $companyData[$schema]
|
if (-not $matchingFile) {
|
||||||
DumpFile = $matchingFile.FullName
|
$escaped = [regex]::Escape($schema)
|
||||||
DumpSize = [math]::Round($matchingFile.Length / 1MB, 2)
|
$prefixed = @($dumpFiles | Where-Object { $_.BaseName -imatch "^$escaped[_\.]" })
|
||||||
}
|
|
||||||
}
|
if ($prefixed.Count -eq 1) {
|
||||||
else {
|
$matchingFile = $prefixed[0]
|
||||||
$notFoundList += $schema
|
}
|
||||||
}
|
elseif ($prefixed.Count -gt 1) {
|
||||||
}
|
$nume = ($prefixed | ForEach-Object { $_.Name }) -join ', '
|
||||||
|
Write-LogWarning " - ${schema}: $($prefixed.Count) DMP-uri ambigue ($nume) - redenumeste-l pe cel bun in $schema.dmp"
|
||||||
Write-Log "Companies to import: $($importList.Count)"
|
}
|
||||||
if ($notFoundList.Count -gt 0) {
|
}
|
||||||
Write-LogWarning "Companies without matching dump file: $($notFoundList.Count)"
|
|
||||||
foreach ($schema in $notFoundList) {
|
if ($matchingFile) {
|
||||||
Write-Log " - $schema (no DMP file found)"
|
$importList += [PSCustomObject]@{
|
||||||
}
|
Schema = $schema
|
||||||
}
|
Password = $companyData[$schema]
|
||||||
|
DumpFile = $matchingFile.FullName
|
||||||
if ($importList.Count -eq 0) {
|
DumpSize = [math]::Round($matchingFile.Length / 1MB, 2)
|
||||||
Write-LogWarning "No companies to import"
|
}
|
||||||
Close-LogFile -Success $true
|
}
|
||||||
exit 0
|
else {
|
||||||
}
|
$notFoundList += $schema
|
||||||
|
}
|
||||||
# Display import plan
|
}
|
||||||
Write-LogSection "Import Plan"
|
|
||||||
|
Write-Log "Companies to import: $($importList.Count)"
|
||||||
$totalSize = ($importList | Measure-Object -Property DumpSize -Sum).Sum
|
if ($notFoundList.Count -gt 0) {
|
||||||
Write-Log "Total data to import: $totalSize MB"
|
Write-LogWarning "Companies without matching dump file: $($notFoundList.Count)"
|
||||||
Write-Log ""
|
foreach ($schema in $notFoundList) {
|
||||||
Write-Log "Companies to import:"
|
Write-Log " - $schema (no DMP file found)"
|
||||||
foreach ($item in $importList) {
|
}
|
||||||
Write-Log " - $($item.Schema): $($item.DumpFile) ($($item.DumpSize) MB)"
|
}
|
||||||
}
|
|
||||||
|
if ($importList.Count -eq 0) {
|
||||||
if ($DryRun) {
|
Write-LogWarning "No companies to import"
|
||||||
Write-LogSection "Dry Run Complete"
|
Close-LogFile -Success $true
|
||||||
Write-Log "Would import $($importList.Count) company schemas"
|
exit 0
|
||||||
Close-LogFile -Success $true
|
}
|
||||||
exit 0
|
|
||||||
}
|
# Display import plan
|
||||||
|
Write-LogSection "Import Plan"
|
||||||
# Ensure DMPDIR exists
|
|
||||||
$dmpDir = "C:\DMPDIR"
|
$totalSize = ($importList | Measure-Object -Property DumpSize -Sum).Sum
|
||||||
if (-not (Test-Path -Path $dmpDir)) {
|
Write-Log "Total data to import: $totalSize MB"
|
||||||
New-Item -ItemType Directory -Path $dmpDir -Force | Out-Null
|
Write-Log ""
|
||||||
}
|
Write-Log "Companies to import:"
|
||||||
|
foreach ($item in $importList) {
|
||||||
# Process each company
|
Write-Log " - $($item.Schema): $($item.DumpFile) ($($item.DumpSize) MB)"
|
||||||
Write-LogSection "Importing Companies"
|
}
|
||||||
|
|
||||||
$successCount = 0
|
if ($DryRun) {
|
||||||
$failCount = 0
|
Write-LogSection "Dry Run Complete"
|
||||||
$startTime = Get-Date
|
Write-Log "Would import $($importList.Count) company schemas"
|
||||||
|
Close-LogFile -Success $true
|
||||||
foreach ($item in $importList) {
|
exit 0
|
||||||
Write-LogSection "Importing $($item.Schema)"
|
}
|
||||||
|
|
||||||
try {
|
# Ensure DMPDIR exists
|
||||||
# Check if user already exists
|
$dmpDir = if ($DmpDir) { $DmpDir } else { $DumpDirectory }
|
||||||
$userExists = Test-OracleUser -OracleHome $oraHome -ServiceName $ServiceName `
|
if (-not (Test-Path -Path $dmpDir)) {
|
||||||
-Password $SystemPassword -SchemaName $item.Schema
|
New-Item -ItemType Directory -Path $dmpDir -Force | Out-Null
|
||||||
|
}
|
||||||
if ($userExists) {
|
|
||||||
Write-Log "User $($item.Schema) already exists"
|
# Process each company
|
||||||
|
Write-LogSection "Importing Companies"
|
||||||
# Get current object count
|
|
||||||
$beforeCounts = Get-SchemaObjectCount -OracleHome $oraHome -ServiceName $ServiceName `
|
$successCount = 0
|
||||||
-Password $SystemPassword -SchemaName $item.Schema
|
$failCount = 0
|
||||||
|
$startTime = Get-Date
|
||||||
$beforeTotal = if ($beforeCounts['TOTAL']) { $beforeCounts['TOTAL'] } else { 0 }
|
|
||||||
Write-Log "Existing objects: $beforeTotal"
|
foreach ($item in $importList) {
|
||||||
}
|
Write-LogSection "Importing $($item.Schema)"
|
||||||
else {
|
|
||||||
# Create user
|
try {
|
||||||
Write-Log "Creating user $($item.Schema)..."
|
# Check if user already exists
|
||||||
|
$userExists = Test-OracleUser -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
$createUserSql = @"
|
-Password $SystemPassword -SchemaName $item.Schema
|
||||||
SET ECHO OFF FEEDBACK ON VERIFY OFF
|
|
||||||
|
if ($userExists) {
|
||||||
CREATE USER $($item.Schema)
|
Write-Log "User $($item.Schema) already exists"
|
||||||
IDENTIFIED BY "$($item.Password)"
|
|
||||||
DEFAULT TABLESPACE ROA
|
# Get current object count
|
||||||
TEMPORARY TABLESPACE TEMP
|
$beforeCounts = Get-SchemaObjectCount -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
PROFILE DEFAULT;
|
-Password $SystemPassword -SchemaName $item.Schema
|
||||||
|
|
||||||
GRANT CONNECT TO $($item.Schema);
|
$beforeTotal = if ($beforeCounts['TOTAL']) { $beforeCounts['TOTAL'] } else { 0 }
|
||||||
GRANT RESOURCE TO $($item.Schema);
|
Write-Log "Existing objects: $beforeTotal"
|
||||||
GRANT CREATE MATERIALIZED VIEW TO $($item.Schema);
|
}
|
||||||
GRANT CREATE PROCEDURE TO $($item.Schema);
|
else {
|
||||||
GRANT CREATE SEQUENCE TO $($item.Schema);
|
# Create user
|
||||||
GRANT CREATE TABLE TO $($item.Schema);
|
Write-Log "Creating user $($item.Schema)..."
|
||||||
GRANT CREATE TRIGGER TO $($item.Schema);
|
|
||||||
GRANT CREATE VIEW TO $($item.Schema);
|
$createUserSql = @"
|
||||||
GRANT DEBUG CONNECT SESSION TO $($item.Schema);
|
SET ECHO OFF FEEDBACK ON VERIFY OFF
|
||||||
GRANT SELECT ANY TABLE TO $($item.Schema);
|
|
||||||
GRANT CREATE TYPE TO $($item.Schema);
|
CREATE USER $($item.Schema)
|
||||||
GRANT UNLIMITED TABLESPACE TO $($item.Schema);
|
IDENTIFIED BY "$($item.Password)"
|
||||||
|
DEFAULT TABLESPACE ROA
|
||||||
COMMIT;
|
TEMPORARY TABLESPACE TEMP
|
||||||
SELECT 'USER_CREATED' FROM dual;
|
PROFILE DEFAULT;
|
||||||
EXIT;
|
|
||||||
"@
|
GRANT CONNECT TO $($item.Schema);
|
||||||
|
GRANT RESOURCE TO $($item.Schema);
|
||||||
$createResult = Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
GRANT CREATE MATERIALIZED VIEW TO $($item.Schema);
|
||||||
-Username "SYSTEM" -Password $SystemPassword -SqlCommand $createUserSql -Silent
|
GRANT CREATE PROCEDURE TO $($item.Schema);
|
||||||
|
GRANT CREATE SEQUENCE TO $($item.Schema);
|
||||||
if ($createResult -match "USER_CREATED") {
|
GRANT CREATE TABLE TO $($item.Schema);
|
||||||
Write-LogSuccess "User $($item.Schema) created"
|
GRANT CREATE TRIGGER TO $($item.Schema);
|
||||||
}
|
GRANT CREATE VIEW TO $($item.Schema);
|
||||||
else {
|
GRANT DEBUG CONNECT SESSION TO $($item.Schema);
|
||||||
throw "Failed to create user $($item.Schema)"
|
GRANT SELECT ANY TABLE TO $($item.Schema);
|
||||||
}
|
GRANT CREATE TYPE TO $($item.Schema);
|
||||||
}
|
GRANT UNLIMITED TABLESPACE TO $($item.Schema);
|
||||||
|
|
||||||
# Copy dump file to DMPDIR if not already there
|
COMMIT;
|
||||||
$dumpFileName = Split-Path -Path $item.DumpFile -Leaf
|
SELECT 'USER_CREATED' FROM dual;
|
||||||
$targetDumpPath = Join-Path $dmpDir $dumpFileName
|
EXIT;
|
||||||
|
"@
|
||||||
if ($item.DumpFile -ne $targetDumpPath) {
|
|
||||||
Write-Log "Copying dump file to DMPDIR..."
|
$createResult = Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
Copy-Item -Path $item.DumpFile -Destination $targetDumpPath -Force
|
-Username "SYSTEM" -Password $SystemPassword -SqlCommand $createUserSql -Silent
|
||||||
}
|
|
||||||
|
if ($createResult -match "USER_CREATED") {
|
||||||
# Run import
|
Write-LogSuccess "User $($item.Schema) created"
|
||||||
Write-Log "Running impdp for $($item.Schema)..."
|
}
|
||||||
|
else {
|
||||||
$impdpPath = Join-Path $oraHome "bin\impdp.exe"
|
throw "Failed to create user $($item.Schema)"
|
||||||
$importLogFile = "$($item.Schema)_import_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
|
}
|
||||||
|
}
|
||||||
# Use EZConnect format for impdp (handles listener bound to specific IP)
|
|
||||||
$dbHost = Get-ListenerHost -OracleHome $oraHome
|
# Copy dump file to DMPDIR if not already there
|
||||||
$connString = "SYSTEM/`"$SystemPassword`"@${dbHost}:1521/$ServiceName"
|
$dumpFileName = Split-Path -Path $item.DumpFile -Leaf
|
||||||
|
$targetDumpPath = Join-Path $dmpDir $dumpFileName
|
||||||
# Check if dump has different schema name (remapping needed)
|
|
||||||
$remapParam = ""
|
if ($item.DumpFile -ne $targetDumpPath) {
|
||||||
$dumpBaseName = [System.IO.Path]::GetFileNameWithoutExtension($dumpFileName).ToUpper()
|
Write-Log "Copying dump file to DMPDIR..."
|
||||||
if ($dumpBaseName -ne $item.Schema) {
|
Copy-Item -Path $item.DumpFile -Destination $targetDumpPath -Force
|
||||||
$remapParam = "remap_schema=$dumpBaseName`:$($item.Schema)"
|
}
|
||||||
Write-Log "Schema remap: $dumpBaseName -> $($item.Schema)"
|
|
||||||
}
|
# Run import
|
||||||
|
Write-Log "Running impdp for $($item.Schema)..."
|
||||||
$impdpParams = @(
|
|
||||||
"`"$connString`"",
|
$impdpPath = Join-Path $oraHome "bin\impdp.exe"
|
||||||
"directory=DMPDIR",
|
$importLogFile = "$($item.Schema)_import_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
|
||||||
"dumpfile=$dumpFileName",
|
|
||||||
"logfile=$importLogFile",
|
# Use EZConnect format for impdp (handles listener bound to specific IP)
|
||||||
"schemas=$($item.Schema)",
|
$dbHost = Get-ListenerHost -OracleHome $oraHome
|
||||||
"table_exists_action=REPLACE",
|
$connString = "SYSTEM/`"$SystemPassword`"@${dbHost}:1521/$ServiceName"
|
||||||
"parallel=1" # Required for Oracle XE
|
|
||||||
)
|
# Check if dump has different schema name (remapping needed)
|
||||||
|
$remapParam = ""
|
||||||
if ($remapParam) {
|
$dumpBaseName = [System.IO.Path]::GetFileNameWithoutExtension($dumpFileName).ToUpper()
|
||||||
$impdpParams += $remapParam
|
if ($dumpBaseName -ne $item.Schema) {
|
||||||
}
|
$remapParam = "remap_schema=$dumpBaseName`:$($item.Schema)"
|
||||||
|
Write-Log "Schema remap: $dumpBaseName -> $($item.Schema)"
|
||||||
$arguments = $impdpParams -join " "
|
}
|
||||||
|
|
||||||
# Set Oracle environment
|
$impdpParams = @(
|
||||||
$env:ORACLE_HOME = $oraHome
|
"`"$connString`"",
|
||||||
$env:PATH = "$oraHome\bin;$env:PATH"
|
"directory=DMPDIR",
|
||||||
$env:NLS_LANG = "AMERICAN_AMERICA.AL32UTF8"
|
"dumpfile=$dumpFileName",
|
||||||
|
"logfile=$importLogFile",
|
||||||
$importStart = Get-Date
|
"schemas=$($item.Schema)",
|
||||||
$process = Start-Process -FilePath $impdpPath -ArgumentList $arguments -Wait -NoNewWindow -PassThru
|
"table_exists_action=REPLACE",
|
||||||
|
"parallel=1" # Required for Oracle XE
|
||||||
$importDuration = (Get-Date) - $importStart
|
)
|
||||||
Write-Log "Import completed in $([math]::Round($importDuration.TotalMinutes, 2)) minutes"
|
|
||||||
|
if ($remapParam) {
|
||||||
# Verify import
|
$impdpParams += $remapParam
|
||||||
$afterCounts = Get-SchemaObjectCount -OracleHome $oraHome -ServiceName $ServiceName `
|
}
|
||||||
-Password $SystemPassword -SchemaName $item.Schema
|
|
||||||
|
$arguments = $impdpParams -join " "
|
||||||
$afterTotal = if ($afterCounts['TOTAL']) { $afterCounts['TOTAL'] } else { 0 }
|
|
||||||
$afterInvalid = if ($afterCounts['INVALID']) { $afterCounts['INVALID'] } else { 0 }
|
# Set Oracle environment
|
||||||
|
$env:ORACLE_HOME = $oraHome
|
||||||
Write-Log "Objects after import: $afterTotal"
|
$env:PATH = "$oraHome\bin;$env:PATH"
|
||||||
|
$env:NLS_LANG = "AMERICAN_AMERICA.AL32UTF8"
|
||||||
if ($afterInvalid -gt 0) {
|
|
||||||
Write-LogWarning "Invalid objects: $afterInvalid"
|
$importStart = Get-Date
|
||||||
|
$process = Start-Process -FilePath $impdpPath -ArgumentList $arguments -Wait -NoNewWindow -PassThru
|
||||||
# Recompile
|
|
||||||
$recompileSql = @"
|
$importDuration = (Get-Date) - $importStart
|
||||||
BEGIN
|
Write-Log "Import completed in $([math]::Round($importDuration.TotalMinutes, 2)) minutes"
|
||||||
DBMS_UTILITY.COMPILE_SCHEMA('$($item.Schema)', FALSE);
|
|
||||||
END;
|
# Verify import
|
||||||
/
|
$afterCounts = Get-SchemaObjectCount -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
EXIT;
|
-Password $SystemPassword -SchemaName $item.Schema
|
||||||
"@
|
|
||||||
Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
$afterTotal = if ($afterCounts['TOTAL']) { $afterCounts['TOTAL'] } else { 0 }
|
||||||
-Username "SYSTEM" -Password $SystemPassword -SqlCommand $recompileSql -Silent
|
$afterInvalid = if ($afterCounts['INVALID']) { $afterCounts['INVALID'] } else { 0 }
|
||||||
}
|
|
||||||
|
Write-Log "Objects after import: $afterTotal"
|
||||||
if ($process.ExitCode -eq 0) {
|
|
||||||
Write-LogSuccess "$($item.Schema) imported successfully ($afterTotal objects)"
|
if ($afterInvalid -gt 0) {
|
||||||
$successCount++
|
Write-LogWarning "Invalid objects: $afterInvalid"
|
||||||
}
|
|
||||||
else {
|
# Recompile
|
||||||
Write-LogWarning "$($item.Schema) import completed with warnings"
|
$recompileSql = @"
|
||||||
$successCount++
|
BEGIN
|
||||||
}
|
DBMS_UTILITY.COMPILE_SCHEMA('$($item.Schema)', FALSE);
|
||||||
|
END;
|
||||||
# Clean up copied dump file
|
/
|
||||||
if ($item.DumpFile -ne $targetDumpPath -and (Test-Path -Path $targetDumpPath)) {
|
EXIT;
|
||||||
Remove-Item -Path $targetDumpPath -Force -ErrorAction SilentlyContinue
|
"@
|
||||||
}
|
Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
}
|
-Username "SYSTEM" -Password $SystemPassword -SqlCommand $recompileSql -Silent
|
||||||
catch {
|
}
|
||||||
Write-LogError "Failed to import $($item.Schema): $_"
|
|
||||||
$failCount++
|
if ($process.ExitCode -eq 0) {
|
||||||
}
|
Write-LogSuccess "$($item.Schema) imported successfully ($afterTotal objects)"
|
||||||
}
|
$successCount++
|
||||||
|
}
|
||||||
$totalDuration = (Get-Date) - $startTime
|
else {
|
||||||
|
Write-LogWarning "$($item.Schema) import completed with warnings"
|
||||||
# Summary
|
$successCount++
|
||||||
Write-LogSection "Import Complete"
|
}
|
||||||
|
|
||||||
Write-LogSuccess "Company import batch completed!"
|
# Clean up copied dump file
|
||||||
Write-Log ""
|
if ($item.DumpFile -ne $targetDumpPath -and (Test-Path -Path $targetDumpPath)) {
|
||||||
Write-Log "Summary:"
|
Remove-Item -Path $targetDumpPath -Force -ErrorAction SilentlyContinue
|
||||||
Write-Log " Total companies: $($importList.Count)"
|
}
|
||||||
Write-Log " Successful: $successCount"
|
}
|
||||||
Write-Log " Failed: $failCount"
|
catch {
|
||||||
Write-Log " Total duration: $([math]::Round($totalDuration.TotalMinutes, 2)) minutes"
|
Write-LogError "Failed to import $($item.Schema): $_"
|
||||||
Write-Log ""
|
$failCount++
|
||||||
|
}
|
||||||
if ($notFoundList.Count -gt 0) {
|
}
|
||||||
Write-Log "Companies skipped (no dump file):"
|
|
||||||
foreach ($schema in $notFoundList) {
|
$totalDuration = (Get-Date) - $startTime
|
||||||
Write-Log " - $schema"
|
|
||||||
}
|
# Summary
|
||||||
}
|
Write-LogSection "Import Complete"
|
||||||
|
|
||||||
Write-Log ""
|
Write-LogSuccess "Company import batch completed!"
|
||||||
Write-Log "Next steps:"
|
Write-Log ""
|
||||||
Write-Log " 1. Run 07-verify-installation.ps1 to verify all schemas"
|
Write-Log "Summary:"
|
||||||
|
Write-Log " Total companies: $($importList.Count)"
|
||||||
Close-LogFile -Success ($failCount -eq 0)
|
Write-Log " Successful: $successCount"
|
||||||
exit $(if ($failCount -eq 0) { 0 } else { 1 })
|
Write-Log " Failed: $failCount"
|
||||||
}
|
Write-Log " Total duration: $([math]::Round($totalDuration.TotalMinutes, 2)) minutes"
|
||||||
catch {
|
Write-Log ""
|
||||||
Write-LogError "Import failed: $_"
|
|
||||||
Write-LogError $_.ScriptStackTrace
|
if ($notFoundList.Count -gt 0) {
|
||||||
Close-LogFile -Success $false
|
Write-Log "Companies skipped (no dump file):"
|
||||||
exit 1
|
foreach ($schema in $notFoundList) {
|
||||||
}
|
Write-Log " - $schema"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Log ""
|
||||||
|
Write-Log "Next steps:"
|
||||||
|
Write-Log " 1. Run 07-verify-installation.ps1 to verify all schemas"
|
||||||
|
|
||||||
|
Close-LogFile -Success ($failCount -eq 0)
|
||||||
|
exit $(if ($failCount -eq 0) { 0 } else { 1 })
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
Write-LogError "Import failed: $_"
|
||||||
|
Write-LogError $_.ScriptStackTrace
|
||||||
|
Close-LogFile -Success $false
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,327 +1,333 @@
|
|||||||
#Requires -Version 5.1
|
#Requires -Version 5.1
|
||||||
|
|
||||||
<#
|
<#
|
||||||
.SYNOPSIS
|
.SYNOPSIS
|
||||||
Add a new company schema to ROA Oracle.
|
Add a new company schema to ROA Oracle.
|
||||||
|
|
||||||
.DESCRIPTION
|
.DESCRIPTION
|
||||||
Creates a new company user/schema with either:
|
Creates a new company user/schema with either:
|
||||||
- Import from a template DMP file
|
- Import from a template DMP file
|
||||||
- Empty schema with basic structures
|
- Empty schema with basic structures
|
||||||
|
|
||||||
.PARAMETER CompanyName
|
.PARAMETER CompanyName
|
||||||
Schema name for the new company. Required. Must be uppercase alphanumeric.
|
Schema name for the new company. Required. Must be uppercase alphanumeric.
|
||||||
|
|
||||||
.PARAMETER Password
|
.PARAMETER Password
|
||||||
Password for the new company schema. Default: ROMFASTSOFT
|
Password for the new company schema. Default: ROMFASTSOFT
|
||||||
|
|
||||||
.PARAMETER OracleHome
|
.PARAMETER OracleHome
|
||||||
Oracle home directory. If not specified, auto-detects.
|
Oracle home directory. If not specified, auto-detects.
|
||||||
|
|
||||||
.PARAMETER ServiceName
|
.PARAMETER ServiceName
|
||||||
Database service name. Default: XEPDB1
|
Database service name. Default: XEPDB1
|
||||||
|
|
||||||
.PARAMETER SystemPassword
|
.PARAMETER SystemPassword
|
||||||
SYSTEM user password. Default: romfastsoft
|
SYSTEM user password. Default: romfastsoft
|
||||||
|
|
||||||
.PARAMETER TemplateDump
|
.PARAMETER TemplateDump
|
||||||
Optional path to a template DMP file to import.
|
Optional path to a template DMP file to import.
|
||||||
|
|
||||||
.PARAMETER TemplateSchema
|
.PARAMETER TemplateSchema
|
||||||
Schema name in the template DMP file if different from target (for remap).
|
Schema name in the template DMP file if different from target (for remap).
|
||||||
|
|
||||||
.PARAMETER Force
|
.PARAMETER Force
|
||||||
Drop and recreate if user already exists.
|
Drop and recreate if user already exists.
|
||||||
|
|
||||||
.EXAMPLE
|
.EXAMPLE
|
||||||
.\06-add-company.ps1 -CompanyName "NEWCOMPANY"
|
.\06-add-company.ps1 -CompanyName "NEWCOMPANY"
|
||||||
|
|
||||||
.EXAMPLE
|
.EXAMPLE
|
||||||
.\06-add-company.ps1 -CompanyName "FIRMA2024" -Password "SecurePass123"
|
.\06-add-company.ps1 -CompanyName "FIRMA2024" -Password "SecurePass123"
|
||||||
|
|
||||||
.EXAMPLE
|
.EXAMPLE
|
||||||
.\06-add-company.ps1 -CompanyName "NEWFIRMA" -TemplateDump "C:\dumps\FIRMANOUA.dmp" -TemplateSchema "FIRMANOUA"
|
.\06-add-company.ps1 -CompanyName "NEWFIRMA" -TemplateDump "C:\dumps\FIRMANOUA.dmp" -TemplateSchema "FIRMANOUA"
|
||||||
|
|
||||||
.NOTES
|
.NOTES
|
||||||
File Name : 06-add-company.ps1
|
File Name : 06-add-company.ps1
|
||||||
Prerequisite : Run 04-create-synonyms-grants.ps1 first
|
Prerequisite : Run 04-create-synonyms-grants.ps1 first
|
||||||
Copyright 2024 : ROMFAST
|
Copyright 2024 : ROMFAST
|
||||||
#>
|
#>
|
||||||
|
|
||||||
[CmdletBinding()]
|
[CmdletBinding()]
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory = $true)]
|
[Parameter(Mandatory = $true)]
|
||||||
[ValidatePattern('^[A-Z0-9_]+$')]
|
[ValidatePattern('^[A-Z0-9_]+$')]
|
||||||
[string]$CompanyName,
|
[string]$CompanyName,
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[string]$Password = "ROMFASTSOFT",
|
[string]$Password = "ROMFASTSOFT",
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[string]$OracleHome,
|
[string]$OracleHome,
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[string]$ServiceName = "XEPDB1",
|
[string]$ServiceName = "XEPDB1",
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[string]$SystemPassword = "romfastsoft",
|
[string]$SystemPassword = "romfastsoft",
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[ValidateScript({ Test-Path $_ })]
|
[ValidateScript({ Test-Path $_ })]
|
||||||
[string]$TemplateDump,
|
[string]$TemplateDump,
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[string]$TemplateSchema,
|
[string]$TemplateSchema,
|
||||||
|
|
||||||
[Parameter(Mandatory = $false)]
|
[Parameter(Mandatory = $false)]
|
||||||
[switch]$Force
|
[switch]$Force,
|
||||||
)
|
|
||||||
|
# Calea fizica a directorului Oracle DMPDIR, asa cum a fost pusa la instalare.
|
||||||
$ErrorActionPreference = 'Stop'
|
[Parameter(Mandatory = $false)]
|
||||||
|
[string]$DmpDir = "C:\DMPDIR"
|
||||||
# Ensure company name is uppercase
|
)
|
||||||
$CompanyName = $CompanyName.ToUpper()
|
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
# Source library functions
|
|
||||||
. "$PSScriptRoot\lib\logging-functions.ps1"
|
# Ensure company name is uppercase
|
||||||
. "$PSScriptRoot\lib\oracle-functions.ps1"
|
$CompanyName = $CompanyName.ToUpper()
|
||||||
|
|
||||||
# Initialize logging
|
# Source library functions
|
||||||
$logPath = Join-Path $PSScriptRoot "..\logs\06-add-company_${CompanyName}_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
|
. "$PSScriptRoot\lib\logging-functions.ps1"
|
||||||
Initialize-LogFile -LogPath $logPath -ScriptName "06-add-company.ps1"
|
. "$PSScriptRoot\lib\oracle-functions.ps1"
|
||||||
|
|
||||||
try {
|
# Initialize logging
|
||||||
Write-LogSection "Adding New Company: $CompanyName"
|
$logPath = Join-Path $PSScriptRoot "..\logs\06-add-company_${CompanyName}_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
|
||||||
|
Initialize-LogFile -LogPath $logPath -ScriptName "06-add-company.ps1"
|
||||||
# Validate Oracle installation
|
|
||||||
$oraHome = Get-OracleHome -OracleHome $OracleHome
|
try {
|
||||||
Write-LogSuccess "Oracle Home: $oraHome"
|
Write-LogSection "Adding New Company: $CompanyName"
|
||||||
|
|
||||||
# Test connection
|
# Validate Oracle installation
|
||||||
Write-Log "Testing database connection..."
|
$oraHome = Get-OracleHome -OracleHome $OracleHome
|
||||||
if (-not (Test-OracleConnection -OracleHome $oraHome -ServiceName $ServiceName `
|
Write-LogSuccess "Oracle Home: $oraHome"
|
||||||
-Password $SystemPassword)) {
|
|
||||||
throw "Cannot connect to database. Please verify ServiceName and SystemPassword."
|
# Test connection
|
||||||
}
|
Write-Log "Testing database connection..."
|
||||||
Write-LogSuccess "Database connection successful"
|
if (-not (Test-OracleConnection -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
|
-Password $SystemPassword)) {
|
||||||
# Check if user already exists
|
throw "Cannot connect to database. Please verify ServiceName and SystemPassword."
|
||||||
Write-Log "Checking if user $CompanyName exists..."
|
}
|
||||||
$userExists = Test-OracleUser -OracleHome $oraHome -ServiceName $ServiceName `
|
Write-LogSuccess "Database connection successful"
|
||||||
-Password $SystemPassword -SchemaName $CompanyName
|
|
||||||
|
# Check if user already exists
|
||||||
if ($userExists) {
|
Write-Log "Checking if user $CompanyName exists..."
|
||||||
if ($Force) {
|
$userExists = Test-OracleUser -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
Write-LogWarning "User $CompanyName exists. Dropping due to -Force flag..."
|
-Password $SystemPassword -SchemaName $CompanyName
|
||||||
|
|
||||||
$dropSql = @"
|
if ($userExists) {
|
||||||
SET ECHO OFF FEEDBACK ON VERIFY OFF
|
if ($Force) {
|
||||||
DROP USER $CompanyName CASCADE;
|
Write-LogWarning "User $CompanyName exists. Dropping due to -Force flag..."
|
||||||
SELECT 'USER_DROPPED' FROM dual;
|
|
||||||
EXIT;
|
$dropSql = @"
|
||||||
"@
|
SET ECHO OFF FEEDBACK ON VERIFY OFF
|
||||||
$dropResult = Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
DROP USER $CompanyName CASCADE;
|
||||||
-Username "SYSTEM" -Password $SystemPassword -SqlCommand $dropSql
|
SELECT 'USER_DROPPED' FROM dual;
|
||||||
|
EXIT;
|
||||||
if ($dropResult -match "USER_DROPPED") {
|
"@
|
||||||
Write-Log "User $CompanyName dropped"
|
$dropResult = Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
}
|
-Username "SYSTEM" -Password $SystemPassword -SqlCommand $dropSql
|
||||||
else {
|
|
||||||
throw "Failed to drop user $CompanyName"
|
if ($dropResult -match "USER_DROPPED") {
|
||||||
}
|
Write-Log "User $CompanyName dropped"
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
throw "User $CompanyName already exists. Use -Force to drop and recreate."
|
throw "Failed to drop user $CompanyName"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
else {
|
||||||
# Create user
|
throw "User $CompanyName already exists. Use -Force to drop and recreate."
|
||||||
Write-LogSection "Creating User $CompanyName"
|
}
|
||||||
|
}
|
||||||
$createUserSql = @"
|
|
||||||
SET ECHO OFF FEEDBACK ON VERIFY OFF
|
# Create user
|
||||||
|
Write-LogSection "Creating User $CompanyName"
|
||||||
PROMPT Creating user $CompanyName...
|
|
||||||
CREATE USER $CompanyName
|
$createUserSql = @"
|
||||||
IDENTIFIED BY "$Password"
|
SET ECHO OFF FEEDBACK ON VERIFY OFF
|
||||||
DEFAULT TABLESPACE ROA
|
|
||||||
TEMPORARY TABLESPACE TEMP
|
PROMPT Creating user $CompanyName...
|
||||||
PROFILE DEFAULT;
|
CREATE USER $CompanyName
|
||||||
|
IDENTIFIED BY "$Password"
|
||||||
PROMPT Granting role privileges...
|
DEFAULT TABLESPACE ROA
|
||||||
GRANT CONNECT TO $CompanyName;
|
TEMPORARY TABLESPACE TEMP
|
||||||
GRANT RESOURCE TO $CompanyName;
|
PROFILE DEFAULT;
|
||||||
|
|
||||||
PROMPT Granting system privileges...
|
PROMPT Granting role privileges...
|
||||||
GRANT CREATE MATERIALIZED VIEW TO $CompanyName;
|
GRANT CONNECT TO $CompanyName;
|
||||||
GRANT CREATE PROCEDURE TO $CompanyName;
|
GRANT RESOURCE TO $CompanyName;
|
||||||
GRANT CREATE SEQUENCE TO $CompanyName;
|
|
||||||
GRANT CREATE TABLE TO $CompanyName;
|
PROMPT Granting system privileges...
|
||||||
GRANT CREATE TRIGGER TO $CompanyName;
|
GRANT CREATE MATERIALIZED VIEW TO $CompanyName;
|
||||||
GRANT CREATE VIEW TO $CompanyName;
|
GRANT CREATE PROCEDURE TO $CompanyName;
|
||||||
GRANT DEBUG CONNECT SESSION TO $CompanyName;
|
GRANT CREATE SEQUENCE TO $CompanyName;
|
||||||
GRANT SELECT ANY TABLE TO $CompanyName;
|
GRANT CREATE TABLE TO $CompanyName;
|
||||||
GRANT CREATE TYPE TO $CompanyName;
|
GRANT CREATE TRIGGER TO $CompanyName;
|
||||||
GRANT UNLIMITED TABLESPACE TO $CompanyName;
|
GRANT CREATE VIEW TO $CompanyName;
|
||||||
|
GRANT DEBUG CONNECT SESSION TO $CompanyName;
|
||||||
COMMIT;
|
GRANT SELECT ANY TABLE TO $CompanyName;
|
||||||
SELECT 'USER_CREATED' FROM dual;
|
GRANT CREATE TYPE TO $CompanyName;
|
||||||
EXIT;
|
GRANT UNLIMITED TABLESPACE TO $CompanyName;
|
||||||
"@
|
|
||||||
|
COMMIT;
|
||||||
$createResult = Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
SELECT 'USER_CREATED' FROM dual;
|
||||||
-Username "SYSTEM" -Password $SystemPassword -SqlCommand $createUserSql
|
EXIT;
|
||||||
|
"@
|
||||||
if ($createResult -match "USER_CREATED") {
|
|
||||||
Write-LogSuccess "User $CompanyName created successfully"
|
$createResult = Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
}
|
-Username "SYSTEM" -Password $SystemPassword -SqlCommand $createUserSql
|
||||||
else {
|
|
||||||
Write-LogError "Failed to create user"
|
if ($createResult -match "USER_CREATED") {
|
||||||
Write-LogDebug $createResult
|
Write-LogSuccess "User $CompanyName created successfully"
|
||||||
throw "User creation failed"
|
}
|
||||||
}
|
else {
|
||||||
|
Write-LogError "Failed to create user"
|
||||||
# Import from template if specified
|
Write-LogDebug $createResult
|
||||||
if ($TemplateDump) {
|
throw "User creation failed"
|
||||||
Write-LogSection "Importing from Template"
|
}
|
||||||
|
|
||||||
Write-Log "Template dump: $TemplateDump"
|
# Import from template if specified
|
||||||
|
if ($TemplateDump) {
|
||||||
# Determine template schema for remapping
|
Write-LogSection "Importing from Template"
|
||||||
if (-not $TemplateSchema) {
|
|
||||||
$TemplateSchema = [System.IO.Path]::GetFileNameWithoutExtension($TemplateDump).ToUpper()
|
Write-Log "Template dump: $TemplateDump"
|
||||||
Write-Log "Assuming template schema: $TemplateSchema"
|
|
||||||
}
|
# Determine template schema for remapping
|
||||||
|
if (-not $TemplateSchema) {
|
||||||
# Setup DMPDIR
|
$TemplateSchema = [System.IO.Path]::GetFileNameWithoutExtension($TemplateDump).ToUpper()
|
||||||
$dmpDir = "C:\DMPDIR"
|
Write-Log "Assuming template schema: $TemplateSchema"
|
||||||
if (-not (Test-Path -Path $dmpDir)) {
|
}
|
||||||
New-Item -ItemType Directory -Path $dmpDir -Force | Out-Null
|
|
||||||
}
|
# Setup DMPDIR
|
||||||
|
$dmpDir = $DmpDir
|
||||||
New-OracleDirectory -OracleHome $oraHome -ServiceName $ServiceName `
|
if (-not (Test-Path -Path $dmpDir)) {
|
||||||
-Password $SystemPassword -DirectoryName "DMPDIR" -DirectoryPath $dmpDir
|
New-Item -ItemType Directory -Path $dmpDir -Force | Out-Null
|
||||||
|
}
|
||||||
# Copy dump to DMPDIR
|
|
||||||
$dumpFileName = Split-Path -Path $TemplateDump -Leaf
|
if (-not (New-OracleDirectory -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
$targetDumpPath = Join-Path $dmpDir $dumpFileName
|
-Password $SystemPassword -DirectoryName "DMPDIR" -DirectoryPath $dmpDir)) {
|
||||||
|
throw "Directorul Data Pump DMPDIR ($dmpDir) nu e utilizabil de catre baza."
|
||||||
if ($TemplateDump -ne $targetDumpPath) {
|
}
|
||||||
Write-Log "Copying dump file to DMPDIR..."
|
|
||||||
Copy-Item -Path $TemplateDump -Destination $targetDumpPath -Force
|
# Copy dump to DMPDIR
|
||||||
}
|
$dumpFileName = Split-Path -Path $TemplateDump -Leaf
|
||||||
|
$targetDumpPath = Join-Path $dmpDir $dumpFileName
|
||||||
# Run import with remap
|
|
||||||
Write-Log "Running impdp..."
|
if ($TemplateDump -ne $targetDumpPath) {
|
||||||
|
Write-Log "Copying dump file to DMPDIR..."
|
||||||
$impdpPath = Join-Path $oraHome "bin\impdp.exe"
|
Copy-Item -Path $TemplateDump -Destination $targetDumpPath -Force
|
||||||
$importLogFile = "${CompanyName}_import_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
|
}
|
||||||
|
|
||||||
$connString = "SYSTEM/`"$SystemPassword`"@$ServiceName"
|
# Run import with remap
|
||||||
|
Write-Log "Running impdp..."
|
||||||
$impdpParams = @(
|
|
||||||
"`"$connString`"",
|
$impdpPath = Join-Path $oraHome "bin\impdp.exe"
|
||||||
"directory=DMPDIR",
|
$importLogFile = "${CompanyName}_import_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
|
||||||
"dumpfile=$dumpFileName",
|
|
||||||
"logfile=$importLogFile",
|
$connString = "SYSTEM/`"$SystemPassword`"@$ServiceName"
|
||||||
"remap_schema=$TemplateSchema`:$CompanyName",
|
|
||||||
"table_exists_action=REPLACE"
|
$impdpParams = @(
|
||||||
)
|
"`"$connString`"",
|
||||||
|
"directory=DMPDIR",
|
||||||
$arguments = $impdpParams -join " "
|
"dumpfile=$dumpFileName",
|
||||||
|
"logfile=$importLogFile",
|
||||||
# Set Oracle environment
|
"remap_schema=$TemplateSchema`:$CompanyName",
|
||||||
$env:ORACLE_HOME = $oraHome
|
"table_exists_action=REPLACE"
|
||||||
$env:PATH = "$oraHome\bin;$env:PATH"
|
)
|
||||||
$env:NLS_LANG = "AMERICAN_AMERICA.AL32UTF8"
|
|
||||||
|
$arguments = $impdpParams -join " "
|
||||||
$importStart = Get-Date
|
|
||||||
$process = Start-Process -FilePath $impdpPath -ArgumentList $arguments -Wait -NoNewWindow -PassThru
|
# Set Oracle environment
|
||||||
|
$env:ORACLE_HOME = $oraHome
|
||||||
$importDuration = (Get-Date) - $importStart
|
$env:PATH = "$oraHome\bin;$env:PATH"
|
||||||
Write-Log "Import completed in $([math]::Round($importDuration.TotalMinutes, 2)) minutes"
|
$env:NLS_LANG = "AMERICAN_AMERICA.AL32UTF8"
|
||||||
|
|
||||||
if ($process.ExitCode -eq 0) {
|
$importStart = Get-Date
|
||||||
Write-LogSuccess "Template imported successfully"
|
$process = Start-Process -FilePath $impdpPath -ArgumentList $arguments -Wait -NoNewWindow -PassThru
|
||||||
}
|
|
||||||
else {
|
$importDuration = (Get-Date) - $importStart
|
||||||
Write-LogWarning "Import completed with warnings (exit code: $($process.ExitCode))"
|
Write-Log "Import completed in $([math]::Round($importDuration.TotalMinutes, 2)) minutes"
|
||||||
}
|
|
||||||
|
if ($process.ExitCode -eq 0) {
|
||||||
# Clean up copied dump file
|
Write-LogSuccess "Template imported successfully"
|
||||||
if ($TemplateDump -ne $targetDumpPath -and (Test-Path -Path $targetDumpPath)) {
|
}
|
||||||
Remove-Item -Path $targetDumpPath -Force -ErrorAction SilentlyContinue
|
else {
|
||||||
}
|
Write-LogWarning "Import completed with warnings (exit code: $($process.ExitCode))"
|
||||||
}
|
}
|
||||||
|
|
||||||
# Get final object count
|
# Clean up copied dump file
|
||||||
Write-LogSection "Verifying Schema"
|
if ($TemplateDump -ne $targetDumpPath -and (Test-Path -Path $targetDumpPath)) {
|
||||||
|
Remove-Item -Path $targetDumpPath -Force -ErrorAction SilentlyContinue
|
||||||
$counts = Get-SchemaObjectCount -OracleHome $oraHome -ServiceName $ServiceName `
|
}
|
||||||
-Password $SystemPassword -SchemaName $CompanyName
|
}
|
||||||
|
|
||||||
$totalObjects = if ($counts['TOTAL']) { $counts['TOTAL'] } else { 0 }
|
# Get final object count
|
||||||
$invalidObjects = if ($counts['INVALID']) { $counts['INVALID'] } else { 0 }
|
Write-LogSection "Verifying Schema"
|
||||||
|
|
||||||
Write-Log "Total objects: $totalObjects"
|
$counts = Get-SchemaObjectCount -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
|
-Password $SystemPassword -SchemaName $CompanyName
|
||||||
if ($invalidObjects -gt 0) {
|
|
||||||
Write-LogWarning "Invalid objects: $invalidObjects"
|
$totalObjects = if ($counts['TOTAL']) { $counts['TOTAL'] } else { 0 }
|
||||||
|
$invalidObjects = if ($counts['INVALID']) { $counts['INVALID'] } else { 0 }
|
||||||
# Recompile
|
|
||||||
Write-Log "Recompiling invalid objects..."
|
Write-Log "Total objects: $totalObjects"
|
||||||
$recompileSql = @"
|
|
||||||
BEGIN
|
if ($invalidObjects -gt 0) {
|
||||||
DBMS_UTILITY.COMPILE_SCHEMA('$CompanyName', FALSE);
|
Write-LogWarning "Invalid objects: $invalidObjects"
|
||||||
END;
|
|
||||||
/
|
# Recompile
|
||||||
EXIT;
|
Write-Log "Recompiling invalid objects..."
|
||||||
"@
|
$recompileSql = @"
|
||||||
Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
BEGIN
|
||||||
-Username "SYSTEM" -Password $SystemPassword -SqlCommand $recompileSql -Silent
|
DBMS_UTILITY.COMPILE_SCHEMA('$CompanyName', FALSE);
|
||||||
|
END;
|
||||||
# Recheck
|
/
|
||||||
$recheckCounts = Get-SchemaObjectCount -OracleHome $oraHome -ServiceName $ServiceName `
|
EXIT;
|
||||||
-Password $SystemPassword -SchemaName $CompanyName
|
"@
|
||||||
|
Invoke-SqlPlus -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
$recheckInvalid = if ($recheckCounts['INVALID']) { $recheckCounts['INVALID'] } else { 0 }
|
-Username "SYSTEM" -Password $SystemPassword -SqlCommand $recompileSql -Silent
|
||||||
if ($recheckInvalid -lt $invalidObjects) {
|
|
||||||
Write-LogSuccess "Recompilation fixed $($invalidObjects - $recheckInvalid) objects"
|
# Recheck
|
||||||
}
|
$recheckCounts = Get-SchemaObjectCount -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
}
|
-Password $SystemPassword -SchemaName $CompanyName
|
||||||
|
|
||||||
# Test connection with new user
|
$recheckInvalid = if ($recheckCounts['INVALID']) { $recheckCounts['INVALID'] } else { 0 }
|
||||||
Write-Log "Testing connection as $CompanyName..."
|
if ($recheckInvalid -lt $invalidObjects) {
|
||||||
if (Test-OracleConnection -OracleHome $oraHome -ServiceName $ServiceName `
|
Write-LogSuccess "Recompilation fixed $($invalidObjects - $recheckInvalid) objects"
|
||||||
-Username $CompanyName -Password $Password) {
|
}
|
||||||
Write-LogSuccess "Connection test successful"
|
}
|
||||||
}
|
|
||||||
else {
|
# Test connection with new user
|
||||||
Write-LogWarning "Could not connect as $CompanyName"
|
Write-Log "Testing connection as $CompanyName..."
|
||||||
}
|
if (Test-OracleConnection -OracleHome $oraHome -ServiceName $ServiceName `
|
||||||
|
-Username $CompanyName -Password $Password) {
|
||||||
# Summary
|
Write-LogSuccess "Connection test successful"
|
||||||
Write-LogSection "Company Added"
|
}
|
||||||
|
else {
|
||||||
Write-LogSuccess "Company $CompanyName added successfully!"
|
Write-LogWarning "Could not connect as $CompanyName"
|
||||||
Write-Log ""
|
}
|
||||||
Write-Log "Summary:"
|
|
||||||
Write-Log " Schema name: $CompanyName"
|
# Summary
|
||||||
Write-Log " Service: $ServiceName"
|
Write-LogSection "Company Added"
|
||||||
Write-Log " Objects: $totalObjects"
|
|
||||||
if ($TemplateDump) {
|
Write-LogSuccess "Company $CompanyName added successfully!"
|
||||||
Write-Log " Template: $TemplateDump"
|
Write-Log ""
|
||||||
}
|
Write-Log "Summary:"
|
||||||
Write-Log ""
|
Write-Log " Schema name: $CompanyName"
|
||||||
Write-Log "Connection string:"
|
Write-Log " Service: $ServiceName"
|
||||||
Write-Log " $CompanyName/$Password@$ServiceName"
|
Write-Log " Objects: $totalObjects"
|
||||||
|
if ($TemplateDump) {
|
||||||
Close-LogFile -Success $true
|
Write-Log " Template: $TemplateDump"
|
||||||
exit 0
|
}
|
||||||
}
|
Write-Log ""
|
||||||
catch {
|
Write-Log "Connection string:"
|
||||||
Write-LogError "Failed to add company: $_"
|
Write-Log " $CompanyName/$Password@$ServiceName"
|
||||||
Write-LogError $_.ScriptStackTrace
|
|
||||||
Close-LogFile -Success $false
|
Close-LogFile -Success $true
|
||||||
exit 1
|
exit 0
|
||||||
}
|
}
|
||||||
|
catch {
|
||||||
|
Write-LogError "Failed to add company: $_"
|
||||||
|
Write-LogError $_.ScriptStackTrace
|
||||||
|
Close-LogFile -Success $false
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user