Files
DP44/enriched-qwen3-coder-next/DataPRO/Modules/InstallerCustomActions/DBConfiguration.md
2026-04-17 14:55:32 -04:00

93 lines
9.9 KiB
Markdown

---
source_files:
- DataPRO/Modules/InstallerCustomActions/DBConfiguration/MigrationStatus.cs
- DataPRO/Modules/InstallerCustomActions/DBConfiguration/DBConfig.cs
- DataPRO/Modules/InstallerCustomActions/DBConfiguration/CommonUtilities.cs
- DataPRO/Modules/InstallerCustomActions/DBConfiguration/DBTypeChoice.Designer.cs
generated_at: "2026-04-16T04:44:09.733583+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "34f445ff6d14ccf5"
---
# Documentation: DBConfiguration Module
## 1. Purpose
This module provides database configuration and initialization logic for the DataPRO application during installation and migration scenarios. It serves as a standalone executable (`DBConfiguration.exe`) that handles local SQL Server Express LocalDB instance management—including creation, attachment, and detachment of databases (`DataPRO` and `ISO`)—and supports multiple initialization modes (e.g., TSR AIR, Crash, Aero, migration from previous local DB). It also exposes a minimal `MigrationStatus` class for conveying progress during operations. The module is invoked by the installer (via command-line arguments) or standalone (for debugging/testing), and integrates with Windows Forms for interactive configuration when UI is enabled.
## 2. Public Interface
### `DBConfiguration.MigrationStatus`
- **`StatusTypes` enum**: Defines three status categories: `Status`, `MigrationStatus`, and `SourceDb`.
- **`StatusType` property (`StatusTypes`)**: Indicates the type of status being reported.
- **`StatusText` property (`string`)**: Contains the human-readable status message.
### `DBConfiguration.DBConfig`
- **`Main(string[] args)`**: Static entry point. Parses command-line arguments to determine execution mode (installer vs. standalone, UI vs. silent), and dispatches to either `DBTypeChoice` form (interactive) or `CommonUtilities.InitializeDbToTSRAIR()` (TSR AIR initialization). In installer mode, it hides the console window; in standalone command mode, it shows it.
### `DBConfiguration.CommonUtilities`
- **`InitializeDbToTSRAIR(string targetDir)`**: Initializes the database to TSR AIR settings. Performs the following sequence:
1. Calls `ConfigInitializationHelper.UpdateTSRAIRAppSettings(targetDir, true)` (not shown in source; assumed external).
2. Calls `Attach(targetDbDir, scriptsDir)` to attach existing databases.
3. Calls `DbOperations.Connection.Initialize(InitializationTypes.TSRAIR, targetDir)` (assumed external).
4. Calls `Detach(...)` to detach the migrated databases.
5. Shows a success message box.
- **`Attach(string targetDbDir, string scriptsDir)`**: Logs and sets migration status, then calls `InstallDatabase(targetDbDir, "DataPRO", scriptsDir)`.
- **`InstallDatabase(string dBdir, string dbName, string scriptsDir)`**: Performs full LocalDB instance setup:
- Sets connection properties (`Server = Settings.Default.LocalDbDataPROInstance`, `NTLMAuthentication = true`, `usingCentralizedDB = false`, `usingMSSQL = true`).
- Executes SQL LocalDB commands via `ProcessSqlLocalDbCommand(...)` to stop, delete, create, and start the LocalDB instance.
- Attaches `DataPRO.mdf` and `ISO.mdf` databases using `AttachOrDetachDatabase(...)` with `Settings.Default.AttachDBsbat`.
- Returns any error output from SQL commands.
- **`Detach(string sourceDbName, string targetDbDir, string scriptsDir)`**: Detaches the `sourceDbName` (typically `"DataPRO"`) and `ISO` databases using `AttachOrDetachDatabase(...)` with `Settings.Default.DetachDBsbat`. Logs status and shows warnings if errors occur.
- **`SetMigrationStatus(string migrationStatus, bool output = false)`**: Creates and returns a `MigrationStatus` object with `StatusType = StatusTypes.MigrationStatus` and the given `migrationStatus` text. Optionally writes to `Console.WriteLine`.
- **`ProcessSqlLocalDbCommand(string command)`**: Executes a command (e.g., `"start v14.0"`, `"create v14.0"`) against SQL Server LocalDB by:
- Resolving the LocalDB installation path via `GetSqlServerLocalDBPath()`.
- Invoking `sqllocaldb.exe` via `SqlCommandProcessor(...)`.
- Returns non-empty string on error (e.g., `"localdb not installed"`).
- **`GetSqlServerLocalDBPath()`**: Queries the registry (`HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\LocalDB\Installed Versions`) to find the highest installed LocalDB version with a valid `SqlUserInstance.dll` path. Returns the path to the `Tools` directory (e.g., `C:\Program Files\Microsoft SQL Server\140\Tools\`).
- **`AttachOrDetachDatabase(string scriptsDir, string dbName, string sqlDbFileName, string sqlLogFileName, string attachOrDetach)`**: Invokes a batch script (e.g., `AttachDBs.bat`) via `BatchCommandProcessor(...)`. The batch script is expected to use `sqlcmd.exe` to execute `CREATE DATABASE ... FOR ATTACH`.
- **`SqlCommandProcessor(string sqlLocalDbExeFileName, string command)`**: Executes a command-line process (`sqllocaldb.exe`) asynchronously, capturing output via `OutputHandler`. Returns captured output if non-empty.
- **`BatchCommandProcessor(string batchFileName, string dbName, string sqlDbFileName, string sqlLogFileName, string fullSqlcmdPath)`**: Executes a batch file with arguments: `dbName`, quoted `dbFileName`, quoted `logFileName`, and quoted `sqlcmd.exe` path. Uses same async output capture mechanism.
> **Note**: `SetStatus(string status, bool output = false)` is private and used internally; not part of the public interface.
## 3. Invariants
- **LocalDB instance name**: Hardcoded to `"DataPRO"` in `InstallDatabase` and `Attach`. Cannot be changed during TSR AIR Go installation.
- **Database files**: Always expects `DataPRO.mdf`/`DataPRO.ldf` and `ISO.mdf`/`ISO.ldf` in `targetDbDir`.
- **Authentication**: Uses NTLM authentication (`DbOperations._usingNTLMAuthentication = true`) for all LocalDB operations.
- **Centralized DB flag**: `DbOperations._usingCentralizedDB` is explicitly set to `false` during LocalDB operations.
- **Console visibility**: In installer mode (`args.Length > 0` and `noUI != "STANDALONECMD"`), the console window is hidden (`SW_HIDE`). In standalone command mode (`args.Length == 2`), it is shown (`SW_SHOW`).
- **TSR AIR mode**: When `tsrAirGo == true`, the UI (`DBTypeChoice`) is skipped entirely.
- **Registry query**: Only queries 64-bit registry view (`RegistryView.Registry64`).
## 4. Dependencies
### External Dependencies (from imports/includes):
- `System`, `System.Windows.Forms`, `System.Diagnostics`, `System.IO`, `System.Text`, `Microsoft.Win32`
- `DTS.Common.Storage`, `DTS.Common.Enums`, `DTS.Common.Utilities`, `DTS.Common.Utils.Database`
- `DBConfiguration.Properties` (for `Settings.Default`)
### Internal Dependencies:
- `DBTypeChoice` (Windows Form class, defined in `DBTypeChoice.Designer.cs` and implied `DBTypeChoice.cs` not provided).
- `DbOperations` (static class with `Connection` and `_usingCentralizedDB`, `_usingMSSQL`, `_usingNTLMAuthentication` fields; not shown but referenced).
- `ConfigInitializationHelper` (static class with `UpdateTSRAIRAppSettings(...)` method; not shown).
- `Settings.Default`: Used extensively for strings (e.g., `LocalDbFolder`, `ScriptsFolder`, `LocalDbDataPROInstance`, `Mdf`, `LogLdf`, `AttachDBsbat`, `DetachDBsbat`, `StopDataProInstance`, `DeleteDataProInstance`, `CreateDataProInstance`, `StartDataProInstance`, `ISO`, `SqlServerLocalDbNotInstalled`, `Warning`, `InstallationStatus`, `TSRAIRGoInstallationCompletedSuccessfully`, `AttachingPrevLocalDb`, `DetachingLocalMigratedDb`, `DetachingLocalISODb`, `AttachDBsbat`, `DetachDBsbat`, `RegistrySoftwareMicrosoftMicrosoftSQLServerLocalDBInstalledVersions`, `InstanceAPIPath`, `SqlUserInstanceDll`, `LocalDB`, `Tools`, `SqlLocalDBExe`).
### Dependencies on this module:
- The installer (likely WiX or similar) invokes `DBConfig.Main(...)` with specific command-line arguments during installation.
- Other modules may rely on `CommonUtilities` for database setup logic (though only `InitializeDbToTSRAIR` is called from `DBConfig`).
## 5. Gotchas
- **Hardcoded database name**: `"DataPRO"` is hardcoded in `InstallDatabase` and `Attach`. Changing this requires updating multiple locations.
- **Registry path assumptions**: `GetSqlServerLocalDBPath()` assumes a specific registry path (`...\LocalDB\Installed Versions`) and that subkeys are version numbers (e.g., `"11.0"`, `"14.0"`). Failure to parse a subkey as a double silently skips it.
- **`SqlUserInstanceDll` check**: Only considers versions where the `InstanceAPIPath` value ends with `"SqlUserInstance.dll"`. If the path format changes, LocalDB resolution fails.
- **Console window toggling**: The console window is hidden/shown based on `args.Length` and `noUI` value. Misunderstanding the argument semantics may lead to unexpected UI behavior (e.g., window flashing).
- **`tsrAirGo` override**: When `tsrAirGo == true`, the entire `DBTypeChoice` form is skipped—even if `noUI != "TRUE"`. This may conflict with expectations if `noUI` is `"TRUE"` but `tsrAirGo` is also set.
- **Error handling**: Errors from SQL commands are returned as strings and displayed via `MessageBox.Show(...)`, but the method continues execution (e.g., `InstallDatabase` proceeds even if `ProcessSqlLocalDbCommand` returns non-empty). This may leave the system in a partially configured state.
- **`sb` static field**: `CommonUtilities.sb` is a static `StringBuilder` used for output capture. Concurrent calls to `SqlCommandProcessor` or `BatchCommandProcessor` (if ever introduced) would interfere with each other.
- **Missing implementation details**: Key dependencies like `DbOperations.Connection.Initialize(...)`, `ConfigInitializationHelper.UpdateTSRAIRAppSettings(...)`, and `Settings.Default` values are referenced but not defined in the provided source. Their behavior is inferred but not verifiable here.
- **No rollback logic**: If `Attach` succeeds but `Detach` fails, there is no cleanup or error recovery—databases remain attached until manually detached.
- **`ProcessSqlLocalDbCommand` return value**: Returns non-empty string on error, but callers treat *any* non-empty string as a warning (via `MessageBox.Show`) and continue. This may mask critical failures.