Files
DP44/docs/ai/DataPRO/DbAPI/Connections.md
2026-04-17 14:55:32 -04:00

8.2 KiB

source_files, generated_at, model, schema_version, sha256
source_files generated_at model schema_version sha256
DataPRO/DbAPI/Connections/IConnectionDetails.cs
DataPRO/DbAPI/Connections/ConnectionDetails.cs
DataPRO/DbAPI/Connections/IConnections.cs
DataPRO/DbAPI/Connections/ConnectionManager.cs
2026-04-17T15:54:12.769963+00:00 zai-org/GLM-5-FP8 1 2046609d3e9bf292

Documentation: DbAPI.Connections Namespace

1. Purpose

This module manages database connectivity for the DataPRO system, supporting both SQL Server LocalDB instances and remote/centralized databases. It handles the full lifecycle of LocalDB instances (creation, startup, shutdown, deletion, and database attachment), provides user authentication services with both NTLM and username/password modes, and maintains thread-safe tracking of active connections and logged-in users. The module serves as the data access foundation for the broader DataPRO application.


2. Public Interface

IConnectionDetails (Interface)

Properties:

  • bool UseNTLMAuthentication { get; set; } - Controls whether NTLM authentication is used for database connections.
  • string DbUser { get; set; } - Username for database authentication when not using NTLM.
  • string DbUserPassword { get; set; } - Password for database authentication when not using NTLM.
  • string InstanceName { get; set; } - LocalDB instance name.
  • string DbServer { get; set; } - Database server address for remote connections.
  • string DbName { get; set; } - Target database name.
  • bool UsingCentralizedDb { get; set; } - Distinguishes between LocalDB (false) and remote DB (true) modes.
  • string DbFolderPath { get; set; } - Path to database files for LocalDB.
  • string AttachDbsBatPath { get; set; } - Path to attach.bat script for LocalDB database attachment.
  • string ODBCToolsPath { get; set; } - Path to SQLCMD.EXE directory.
  • string SqlDbPath { get; set; } - Path to SQL Server LocalDB installation.
  • int ClientDbVersion { get; set; } - Expected database version from client code.
  • int ConnectionDbVersion { get; set; } - Actual database version being used.

Methods:

  • string GetConnectionString() - Returns a connection string suitable for SqlClient.
  • IConnectionDetails Clone() - Returns a deep copy of the connection details.

ConnectionDetails (Class)

Implements IConnectionDetails.

Constructors:

  • ConnectionDetails() - Default constructor with initialized defaults.
  • ConnectionDetails(ConnectionDetails details) - Copy constructor for cloning.

Default Values:

Property Default Value
UseNTLMAuthentication true
DbUser "DataPROUser"
DbUserPassword "DTSSealBeachHQ"
InstanceName "DataPROInstance"
DbServer @"(localdb)\DataPROInstance"
DbName "DataPRO"
UsingCentralizedDb false
DbFolderPath ""
AttachDbsBatPath ""
SqlDbPath ""
ODBCToolsPath ""

Methods:

  • virtual string GetConnectionString() - Returns cached connection string if available; otherwise builds and caches it. Format depends on UseNTLMAuthentication:
    • NTLM: Server={DbServer};Database={DbName};Trusted_Connection=TRUE;
    • SQL Auth: Server={DbServer};Database={DbName};User Id={DbUser};Password={DbUserPassword};
  • override string ToString() - Returns "{DbServer}\{DbName}" for centralized DB or "Local\{DbName}" for LocalDB.
  • virtual IConnectionDetails Clone() - Returns a new ConnectionDetails copied from the current instance.

IConnections (Interface)

Methods:

  • IConnectionDetails[] GetActiveConnections() - Returns all successfully connected databases.
  • ulong LoginUserHash(IConnectionDetails connection, string user, string hash, out IUserDbRecord userObject) - Authenticates user with a pre-hashed password. Returns 0 (ERROR_SUCCESS) on success, ERROR_LOGINFAILED for failed login, ERROR_UNKNOWN for unexpected errors.
  • ulong LoginUser(IConnectionDetails connection, string user, string password, out IUserDbRecord userObject) - Authenticates user with plaintext password. Returns same error codes as LoginUserHash.
  • ulong ConnectToDb(IConnectionDetails details) - Establishes database connection. Returns 0 on success.
  • bool IsUserLoggedIn(IUserDbRecord user, IConnectionDetails connection) - Checks if a user is currently logged in to a specific database.
  • Tuple<IUserDbRecord, IConnectionDetails>[] GetLoggedInUsers() - Returns all logged-in users across all connected databases.
  • void ClearConnections() - Removes all logged-in users and database connections.

ConnectionManager (Internal Class)

Internal implementation of IConnections. Not exported publicly.

Additional Internal/Static Methods:

  • static ulong GetSqlCommand(IConnectionDetails con, out SqlCommand cmd, string commandText = "") - Creates an open SqlConnection with a SqlCommand. Returns ERROR_SUCCESS or ERROR_UNKNOWN.

Private Methods:

  • ulong Connect(IConnectionDetails details) - Internal connection logic; clones details and routes to ConnectRemote or ConnectLocal.
  • ulong ConnectRemote(IConnectionDetails details) - Handles remote database connections.
  • ulong ConnectLocal(IConnectionDetails details) - Handles LocalDB lifecycle (stop, delete, create, start, attach).
  • void StopInstance(IConnectionDetails details, LogDelegate log) - Stops LocalDB instance.
  • void DeleteInstance(IConnectionDetails details, LogDelegate log) - Deletes LocalDB instance.
  • void CreateInstance(IConnectionDetails details, LogDelegate log) - Creates LocalDB instance.
  • void StartInstance(IConnectionDetails details, LogDelegate log) - Starts LocalDB instance.
  • void AttachDatabases(IConnectionDetails details, LogDelegate log) - Attaches DataPRO and ISO databases.
  • static void AttachDatabase(IConnectionDetails details, string dbName, LogDelegate log) - Attaches a single database via batch file.

3. Invariants

  • Thread Safety: All access to _loggedInUsers is protected by LOGIN_LOCK, and all access to _connections is protected by CONNECT_LOCK.
  • Connection String Caching: GetConnectionString() caches the result in _Connection after first call; subsequent calls return the cached value.
  • Error Code Convention: All public methods returning ulong use 0 to indicate ERROR_SUCCESS. Non-zero values indicate errors.
  • Clone Independence: Clone() produces a deep copy; modifications to the clone do not affect the original.
  • LocalDB Lifecycle Order: When connecting to LocalDB, the system always executes: stop → delete → create → start → attach.
  • Process Synchronization: PROCESS_LOCK ensures only one external process (SqlLocalDB.exe or batch file) runs at a time.
  • Password Hashing Format: LoginUser hashes passwords using SHA256 with format "{password}_{user}" encoded in UTF-8, then Base64-encoded.

4. Dependencies

This module depends on:

  • DbAPI.User - For User.GetUser() and IUserDbRecord.
  • DbAPI.Errors / DbAPI.Logging - For ErrorCodes, LogManager, and LogEvents.
  • DTS.Common.Interface.Database - For IUserDbRecord interface.
  • DTS.Common.Utils.Database - For SqlServerLocalDbException, LogDelegate.
  • DTS.Common.Utilities.Logging - For APILogger.Log.
  • System.Data.SqlClient - For SqlConnection and SqlCommand.
  • System.Security.Cryptography - For SHA256 password hashing.
  • System.Diagnostics - For Process execution.

What depends on this module:

  • Not determinable from the provided source files alone.

5. Gotchas

  1. Hardcoded Default Credentials: ConnectionDetails defaults contain hardcoded credentials (DbUser = "DataPROUser", DbUserPassword = "DTSSealBeachHQ"). These should be overridden in production use.

  2. ConnectRemote Does Not Validate: The ConnectRemote() method unconditionally returns ERROR_SUCCESS without actually validating the connection. The actual connection validation only occurs when GetSqlCommand() is called later.

  3. LocalDB Instance Destruction: Every call to ConnectLocal() destroys and recreates the LocalDB instance. This is destructive and may impact other processes sharing the same instance.

  4. Dual Database Attachment: AttachDatabases() always attempts to attach both the configured DbName database AND a