Files
2026-04-17 14:55:32 -04:00

112 lines
9.1 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
source_files:
- DataPRO/DbAPI/DbAPI.cs
generated_at: "2026-04-16T03:50:14.723059+00:00"
model: "Qwen/Qwen3-Coder-Next-FP8"
schema_version: 1
sha256: "516b972cb7b463d5"
---
# DbAPI
## DbAPI Module Documentation
---
### 1. Purpose
This module serves as the central entry point and facade for database interaction within the DataPRO system. It provides static access to a range of domain-specific data access layers (e.g., sensors, channels, groups, test setups) via singleton-backed properties, while also exposing core database utility functions—most notably for stored procedure version resolution and database version discovery. Its primary role is to abstract database connectivity and version compatibility logic, enabling client code to reliably invoke versioned stored procedures across heterogeneous client-server database environments.
---
### 2. Public Interface
#### Static Methods
| Method | Signature | Behavior |
|--------|-----------|----------|
| `GetStoredProcedureToUse` | `public static ulong GetStoredProcedureToUse(IConnectionDetails connection, string storedProcedure, int clientDbVersion, out int storedProcedureVersionToUse)` | Determines the highest compatible stored procedure version (≤ min(clientDbVersion, serverDbVersion)) by querying the database. Does **not** use caching. Returns `ErrorCodes.ERROR_SUCCESS` on success, or an error code otherwise. |
| `GetStoredProcedureToUseCached` | `public static ulong GetStoredProcedureToUseCached(IConnectionDetails connection, string storedProcedure, int clientDbVersion, out int storedProcedureVersionToUse)` | Same as `GetStoredProcedureToUse`, but caches the mapping `(storedProcedure, clientDbVersion, serverDbVersion) → storedProcedureVersionToUse` in an in-memory dictionary (`_spLookup`) for reuse. Thread-safe via `StoredProcedureLock`. |
| `GetDatabaseVersion` | `public static ulong GetDatabaseVersion(IConnectionDetails connection, out int serverDbVersion)` | Executes stored procedure `sp_DbVersionGet` to retrieve the highest database version number from the server. Returns `ErrorCodes.ERROR_SUCCESS` on success, `ErrorCodes.ERROR_UNKNOWN` on exception. |
| `GetStoredProcedureVersion` | `public static ulong GetStoredProcedureVersion(IConnectionDetails connection, string storedProcedure, int maxSPVersion, out int storedProcedureVersionToUse)` | Executes stored procedure `sp_StoredProcedureVersionsGet` with parameters `@StoredProcedure` and `@Version = maxSPVersion`, then returns the highest version ≤ `maxSPVersion` found. Returns `ErrorCodes.ERROR_SUCCESS` on success, `ErrorCodes.ERROR_UNKNOWN` on exception. |
| `InitializeLogger` | `public static void InitializeLogger(int logSize, string path, int logTypes)` | Initializes the logging subsystem via `Logging.LogManager.Initialize(...)`. Sets internal flag `_loggerInitialized = true`. `logTypes` is a bitmask of `TraceEventType` values (see XML comment for bit definitions). |
| `LogDBCaching` | `public static void LogDBCaching(string message)` | Logs `message` at `TraceEventType.Information` level under event ID `LogManager.LogEvents.Information`. |
#### Static Properties (Singleton Accessors)
| Property | Type | Description |
|----------|------|-------------|
| `Connections` | `IConnections` | Exposes `ConnectionManager` instance for connection management. |
| `Database` | `IDatabase` | Exposes `Database.Database` instance for database-level operations. |
| `DAS` | `IDataRecorders` | Exposes `DataRecorders` instance for data recorder (DAS) operations. |
| `Sensors` | `ISensors` | Exposes `Sensors.Sensors` instance for sensor-related operations. |
| `Graphs` | `IGraphs` | Exposes `Graphs` instance for graph-related operations. |
| `RegionsOfInterest` | `IRegionsOfInterest` | Exposes `RegionsOfInterest` instance for ROI operations. |
| `CalculatedChannels` | `ICalculatedChannels` | Exposes `CalculatedChannels` instance for calculated channel operations. |
| `TestSetups` | `ITestSetups` | Exposes `TestSetups.TestSetups` instance for test setup management. |
| `Tags` | `ITags` | Exposes `Tags.Tags` instance for tag management. |
| `Channels` | `IChannels` | Exposes `Channels.Channels` instance for channel operations. |
| `GroupHardware` | `IGroupHardware` | Exposes `GroupHardware.GroupHardware` instance for group hardware operations. |
| `Groups` | `IGroups` | Exposes `Groups.Groups` instance for group management. |
| `CustomerDetails` | `ICustomerDetails` | Exposes `CustomerDetails.CustomerDetails` instance for customer data operations. |
| `LabratoryDetails` | `ILabratoryDetails` | Exposes `LabratoryDetails.LabratoryDetails` instance for lab data operations. |
| `TestEngineerDetails` | `ITestEngineerDetails` | Exposes `TestEngineerDetails.TestEngineerDetails` instance for test engineer data operations. |
#### Internal Types Referenced
- `SPCache`: Used in `_spLookup`. Contains fields: `ClientVersion`, `DbVersion`, `StoredProcedureVersion`. Instantiated only in `GetStoredProcedureToUseCached`.
- `ErrorCodes`: Source of return codes (e.g., `ERROR_SUCCESS`, `ERROR_UNKNOWN`).
- `Logging.LogManager`: Used for logging; accessed via static methods.
---
### 3. Invariants
- **Version Compatibility**: The version of a stored procedure returned by `GetStoredProcedureToUse`/`GetStoredProcedureToUseCached` is guaranteed to be ≤ both `clientDbVersion` and the servers database version (`serverDbVersion`), as determined by `sp_DbVersionGet`.
- **Stored Procedure Version Resolution**: `GetStoredProcedureVersion` returns the *maximum* version ≤ `maxSPVersion` returned by `sp_StoredProcedureVersionsGet`, or `0` if none found (no explicit error for “not found” beyond return code).
- **Thread Safety**: Caching in `GetStoredProcedureToUseCached` is guarded by a private static lock (`StoredProcedureLock`). The `_spLookup` dictionary is only mutated inside `lock` blocks.
- **Connection Disposal**: All database commands created via `ConnectionManager.GetSqlCommand` are disposed (`cmd.Connection.Dispose()`) in `finally` blocks.
- **Logging Initialization**: `_loggerInitialized` is set to `true` only after `InitializeLogger` completes successfully (no error checking on `InitializeLogger` itself).
- **No Null Checks on Connection**: Methods assume `connection` and `connection.ConnectionDbVersion` are non-null; no defensive checks are present.
---
### 4. Dependencies
#### Internal Dependencies (from source imports)
- `DbAPI.Connections``IConnectionDetails`, `ConnectionManager`, `IConnections`
- `DbAPI.DAS``DataRecorders`, `IDataRecorders`
- `DbAPI.Database``Database.Database`, `IDatabase`
- `DbAPI.Sensors``Sensors.Sensors`, `ISensors`
- `DbAPI.Channels``Channels.Channels`, `IChannels`
- `DbAPI.Groups``Groups.Groups`, `IGroups`
- `DbAPI.GroupHardware``GroupHardware.GroupHardware`, `IGroupHardware`
- `DbAPI.TestSetups``TestSetups.TestSetups`, `ITestSetups`
- `DbAPI.Tags``Tags.Tags`, `ITags`
- `DbAPI.CustomerDetails`, `DbAPI.LabratoryDetails`, `DbAPI.TestEngineerDetails` → respective detail interfaces
- `DbAPI.Errors``ErrorCodes`
- `DbAPI.SPCaching``SPCache`
- `System.Data`, `System.Data.SqlClient``SqlCommand`, `SqlDbType`, `CommandType`, `SqlDataReader`
- `Logging.LogManager` → static logging API (exact location inferred from usage)
#### External Dependencies
- SQL Server (due to use of `SqlClient`, stored procedures `sp_DbVersionGet`, `sp_StoredProcedureVersionsGet`)
- Logging infrastructure (`Logging.LogManager`) — not defined in this file.
#### What Depends on This Module?
- All client modules that require database access (e.g., UI, test execution engine, configuration tools) — inferred from the broad surface area of exposed interfaces.
---
### 5. Gotchas
- **Caching Scope**: `_spLookup` is *per-app-domain* and *not* persisted across application restarts. Cache is never invalidated or cleared.
- **Version Mismatch Risk**: If `clientDbVersion` is outdated relative to the server, `GetStoredProcedureToUseCached` may return a stale version mapping until the cache entry expires (i.e., never, unless app restarts).
- **No Validation of `storedProcedure` Name**: Methods accept any string; SQL injection is mitigated via parameterized queries, but invalid procedure names will cause runtime errors.
- **`GetStoredProcedureVersion` Returns `0` on Failure**: If no matching stored procedure version is found, `storedProcedureVersionToUse` is set to `0`, and `ERROR_SUCCESS` may still be returned — callers must check `storedProcedureVersionToUse != 0` if `0` is not a valid version.
- **`Connection.ConnectionDbVersion` Assumed Valid**: `GetStoredProcedureToUseCached` uses `connection.ConnectionDbVersion` directly; if this property is uninitialized or incorrect, caching will be incorrect.
- **`_loggerInitialized` Not Thread-Safe**: While `InitializeLogger` sets `_loggerInitialized = true`, there is no synchronization or guard against multiple calls or use before initialization.
- **No Timeout Configuration**: Stored procedure execution uses default command timeouts (not shown in source).
- **No Retry Logic**: Transient SQL failures (e.g., network hiccups) are not retried; exceptions result in `ERROR_UNKNOWN`.
None identified beyond those above.