UNPKG

teradatasql

Version:
428 lines 19.1 kB
import { TeradataCursor } from "./teradata-cursor"; import { TeradataLogging } from "./teradata-logging"; export interface ITDConnParams { account?: string; browser?: string; browser_tab_timeout?: string; browser_timeout?: string; column_name?: string; connect_failure_ttl?: string; connect_function?: string; connect_timeout?: string; cop?: string; coplast?: string; database?: string; dbs_port?: string; encryptdata?: string; error_query_count?: string; error_query_interval?: string; error_table_1_suffix?: string; error_table_2_suffix?: string; error_table_database?: string; fake_result_sets?: string; field_quote?: string; field_sep?: string; govern?: string; host?: string; https_port?: string; lob_support?: string; log?: string; logdata?: string; logmech?: string; logon_sequence_number?: string; logon_timeout?: string; manage_error_tables?: string; max_message_body?: string; oidc_scope?: string; oidc_token?: string; partition?: string; password?: string; request_timeout?: string; runstartup?: string; sessions?: string; sip_support?: string; sp_spl?: string; sslca?: string; sslcapath?: string; sslcipher?: string; sslcrc?: string; sslmode?: string; sslprotocol?: string; teradata_values?: string; tmode?: string; user?: string; } export declare function getPackageVersion(): string; export declare class TeradataConnection { static nInstanceCount: number; sVersionNumber: string; private nId; private poolHandle; private gosideLib; private lib; private logLevel; logger: TeradataLogging; private bInAsyncConnect; /** * Registry of all cursors created from this connection. * * This Set tracks all active TeradataCursor instances associated with this * connection to enable cross-object async operation validation. When any * cursor has an async operation in progress (executeAsync/executemanyAsync), * the connection must block ALL operations (both sync and async). * * Lifecycle: * - Cursor registered: When cursor() is called and TeradataCursor is created * - Cursor unregistered: When cursor.close() is called * * Purpose: Enforces "When an async operation is in progress, ALL other operations * are blocked" rule across object boundaries (connection vs cursor). */ private activeCursors; /** * Constants for async operation timing and control. * * These constants centralize timing parameters and control flags used across * all async connection operations, ensuring consistency and maintainability. */ /** * Default timeout duration (in milliseconds) for connectAsync() when logon_timeout is "0" or not specified. * * This constant is used exclusively by connectAsync() as a safety timeout when the logon_timeout * parameter is "0" (default) or explicitly set to "0". While synchronous connect() waits indefinitely * with logon_timeout="0", async operations should always have a safety timeout. The 5-minute duration * provides a reasonable compromise between: * - Honoring user intent of "long wait acceptable" (implied by logon_timeout="0") * - Preventing infinite hangs in async operations * - Allowing slow connections to succeed * * Note: When logon_timeout is set to a positive value, connectAsync() uses that value plus a 5-second * buffer instead of this constant. */ private static readonly CONNECT_ASYNC_DEFAULT_TIMEOUT_MS; /** * Timeout duration (in milliseconds) for closeAsync() operations. * * This constant is used exclusively by closeAsync() to provide client-side timeout protection. * Connection close operations typically complete quickly, so 30 seconds is generous enough * to handle network delays while preventing indefinite hangs. Note: connectAsync() uses * a different timeout strategy based on the logon_timeout parameter. */ private static readonly CLOSE_ASYNC_TIMEOUT_MS; /** * Polling interval (in milliseconds) for connectAsync() and closeAsync() operations. * * This constant controls how frequently the client checks Go-side operation status * during async connection operations. The 100ms interval provides a good balance between: * - Responsiveness: Quick detection of operation completion * - CPU efficiency: Avoiding excessive polling overhead * - Network efficiency: Not overwhelming the Go-side with status requests */ private static readonly POLLING_INTERVAL_MS; /** * Error message constants for async operation enforcement. * * These constants centralize error messages to ensure consistency across methods * and simplify maintenance. They enforce mutual exclusion during async operations. * Made public to allow teradata-cursor.ts to reference them. */ /** * Error message when attempting cursor operations while this cursor's own async operation is in progress. * Used by: TeradataCursor._stopIfInAsyncExecute() */ static readonly ERROR_801_CURSOR_SELF_ASYNC_IN_PROGRESS = "[Error 801] [SQLState HY000] Cannot perform operation while cursor async operation (executeAsync/executemanyAsync) is in progress on this cursor."; /** * Error message when attempting operations while another cursor's async operation is in progress. * Used by: cursor(), TeradataCursor._stopIfInAsyncExecute() */ static readonly ERROR_802_OTHER_CURSOR_ASYNC_IN_PROGRESS = "[Error 802] [SQLState HY000] Cannot perform operation while cursor async operation (executeAsync/executemanyAsync) is in progress on another cursor on this connection"; /** * Error message when attempting new operations while connection async operation is in progress. * Used by: _stopIfInAsyncConnect(), TeradataCursor._stopIfInAsyncExecute() */ static readonly ERROR_803_CONNECTION_ASYNC_IN_PROGRESS = "[Error 803] [SQLState HY000] Cannot perform new operation while connection async operation (connectAsync/closeAsync) is in progress."; /** * Error message when attempting connection async operations while cursor async operation is in progress. * Used by: connectAsync(), closeAsync() */ static readonly ERROR_804_CURSOR_ASYNC_BLOCKS_CONNECTION = "[Error 804] [SQLState HY000] Cannot start new connection async operation (connectAsync/closeAsync) while cursor async operation (executeAsync/executemanyAsync) is in progress."; constructor(); get Id(): number; get uLog(): number; get uPoolHandle(): number | null; get isAsyncConnect(): boolean; get connected(): boolean; cursor(): TeradataCursor; nativeSQL(sSQL: string): string; get autocommit(): boolean; set autocommit(value: boolean); connect(connectParams?: ITDConnParams, sJSON?: string): void; close(): void; cancel(): void; commit(): void; rollback(): void; /** * Asynchronously connects to the Teradata database server using non-blocking operations. * * @param connectParams - Connection parameters (host, user, password, etc.) * @param sJSON - Additional parameters as JSON string (default: "{}") * @returns Promise resolving when connection is established * @throws {ProgrammingError} Error 803 - Connection async operation in progress * @throws {ProgrammingError} Error 804 - Cursor async operation blocks connection operation * @throws {OperationalError} Connection failed * * @example * ```typescript * await conn.connectAsync({ host: "whomooz", user: "guest", password: "please" }); * ``` * * @remarks * **Mutual Exclusion:** ALL new operations blocked while an async operation in progress. * * **Timeout:** Uses 5-minute timeout if logon_timeout=0 (default), otherwise uses logon_timeout + 5s buffer. * * **Polling:** Checks completion every 100ms until done or timeout. */ connectAsync(connectParams?: ITDConnParams, sJSON?: string): Promise<void>; /** * Asynchronously closes the connection using non-blocking operations. * * @returns Promise resolving when connection is closed * @throws {ProgrammingError} Error 803 - Connection async operation already in progress * @throws {ProgrammingError} Error 804 - Cursor async operation blocks connection operation * @throws {OperationalError} Close operation failed * * @example * ```typescript * await conn.closeAsync(); * ``` * * @remarks * **Mutual Exclusion:** ALL operations blocked while async operation in progress. * * **Timeout:** Fixed 30-second timeout for close operations. * * **Polling:** Checks completion every 100ms until done or timeout. * * **Cleanup:** Sets poolHandle to null after successful close. */ closeAsync(): Promise<void>; /** * Prepares connection parameters by merging user params with system metadata. * * This helper method consolidates common parameter preparation logic shared by * both connect() and connectAsync(). It handles: * - JSON kwargs parsing and boolean-to-string conversion * - Stack trace extraction and formatting * - Client metadata injection (kind, VM, OS, stack, extras) * * **Metadata Added:** * - `client_kind`: "S" for Node.js * - `client_vmname`: Node.js version * - `client_osname`: OS version and architecture * - `client_stack`: Formatted call stack * - `client_extra`: Node.js version and timezone * * @param connectParams - User-provided connection parameters * @param sJSON - Additional parameters as JSON string * @returns Merged connection parameters with system metadata * @private */ private _prepareConnectionParams; /** * Validates if an async connect/close operation is currently in progress. * * This method prevents race conditions by ensuring only one async operation * can be active at a time. It's called at the beginning of synchronous and * asynchronous methods to enforce mutual exclusion. * * * @throws {ProgrammingError} Error 803 - If bInAsyncConnect is true, indicating * an async connection operation is already in progress * * @private */ private _stopIfInAsyncConnect; /** * Registers a cursor in the active cursor registry. * * This method adds a TeradataCursor to the activeCursors Set, enabling * cross-object async operation validation. Once registered, the connection * can check if any cursor has an async operation in progress. * * **Lifecycle Integration:** * - Called by: cursor() method when creating new TeradataCursor * - Paired with: _unregisterCursor() called by cursor.close() * * **Purpose:** * - Enables _hasActiveCursorAsyncOp() to detect cursor async operations * - Enforces "When async operation is in progress, ALL other operations are blocked" rule * * @param cursor - The TeradataCursor instance to register * @private */ private _registerCursor; /** * Unregisters a cursor from the active cursor registry. * * This method removes a TeradataCursor from the activeCursors Set when * the cursor is closed. This cleanup ensures accurate async operation * validation state. * * **Lifecycle Integration:** * - Called by: TeradataCursor.close() method * - Paired with: _registerCursor() called by cursor() * * **Purpose:** * - Maintains accurate cursor registry state * - Prevents memory leaks from closed cursors * * @param cursor - The TeradataCursor instance to unregister * @internal - Public for TeradataCursor access, but not part of public API */ _unregisterCursor(cursor: any): void; /** * Checks if any active cursor has an async operation in progress. * * This method provides cross-object async operation validation by checking * if any registered cursor is currently executing an async SQL operation * (executeAsync/executemanyAsync). * * **Validation Logic:** * - Iterates through all cursors in activeCursors Set * - Optionally excludes a specific cursor from the check (used by that cursor to check others) * - Checks each cursor's bInAsyncExecute flag * - Returns true if ANY cursor (except excluded one) has async operation in progress * * **Usage:** * - Called by: connectAsync() and closeAsync() before starting operation * - Called by: cursor() to check if any cursor has async operation before creating new cursor * - Purpose: Enforces "When async operation is in progress, ALL other operations are blocked" * * @param excludeCursor - Optional cursor to exclude from the check (typically the caller) * @returns True if any cursor (except excluded) has async operation in progress, false otherwise * @private */ private _hasActiveCursorAsyncOp; /** * Initiates asynchronous connection creation on the Go side. * * This method starts the async connection process by calling the Go-side * jsgoAsyncCreateConnection function. It handles immediate errors but does * not wait for connection completion - that's handled by polling. * * **Go-side Integration:** * - Calls jsgoAsyncCreateConnection with log level, version, and params * - Handles immediate validation errors from Go side * - Does not block waiting for connection establishment * * **Error Handling:** * - Throws OperationalError for immediate Go-side failures * - Provides timing logs for performance monitoring * - Preserves original Go error messages * * @param nLog - Logging level for Go-side operations * @param sVersionNumber - Driver version number * @param sConnectParams - JSON-serialized connection parameters * @throws {OperationalError} For immediate connection creation failures * * @private */ private _createConnection; /** * Initiates asynchronous connection closure on the Go side. * * This method starts the async connection close process by calling the Go-side * jsgoAsyncCloseConnection function. It validates the handle first and handles * immediate errors, but does not wait for close completion. * * **Pre-conditions:** * - Connection handle should be valid (Go-side will validate) * - No other async operations should be in progress * * **Go-side Integration:** * - Calls jsgoAsyncCloseConnection with log level and pool handle * - Go-side validates handle and provides proper error messages * - Does not block waiting for connection closure completion * * **Error Handling:** * - Go-side performs comprehensive handle validation * - Throws OperationalError for immediate Go-side failures * - Provides timing logs for performance monitoring * - Preserves original Go error messages * * @param nLog - Logging level for Go-side operations * @param nPoolHandle - Connection pool handle to close (Go-side validates) * @throws {OperationalError} For immediate close failures from Go-side validation * * @private */ private _closeConnection; /** * Polls the Go side for async connection operation status. * * This method directly calls the Go-side jsgoPollConnection function to check * if an async operation (connect or close) has completed. It implements the * compatibility fix for the new Go pbReady flag implementation. * * **Go-side Compatibility:** * - Updated for new Go implementation using *pbReady = C.char(1) for completion * - Changed from string-based status to numeric flag (0 = executing, 1 = complete) * - Maintains compatibility with enhanced Go-side error handling * * **Return Values:** * - `number`: 0 = operation still executing, non-zero = operation complete * - `string`: Error message from Go side for immediate failure * * **Error Handling:** * - Go-side validates connection handle with proper error codes * - Returns error string for Go-side failures * - Provides comprehensive timing logs for performance analysis * - Preserves original Go error messages for debugging * * **Performance Monitoring:** * - Logs timing for each poll operation * - Tracks polling frequency and duration * - Enables performance optimization analysis * * @param nLog - Logging level for Go-side operations * @param nPoolHandle - Connection pool handle to poll (Go-side validates) * @returns Operation status as number (0 = executing, non-zero = complete) * or error string for immediate failures * * @private */ private _jsgoPollConnection; /** * Promise wrapper for async connection polling operations. * * This method wraps the synchronous _jsgoPollConnection call in a Promise * to integrate seamlessly with the async/await pattern used in connectAsync() * and closeAsync(). It provides clean separation between sync Go calls and * async JavaScript patterns. * * **Promise Resolution:** * - **Resolves** with numeric result: 0 = operation not complete, non-zero = complete * - **Rejects** with string result: error message from Go side * * **Integration Pattern:** * - Used in while loops within async methods for non-blocking polling * - Enables proper error propagation through Promise rejection * - Maintains clean async/await syntax in calling methods * * **Design Benefits:** * - Clean separation of sync Go calls from async JavaScript patterns * - Consistent error handling through Promise rejection * - Enables timeout handling in calling methods * - Provides foundation for future polling enhancements * * @param nLog - Logging level for Go-side operations * @param nPoolHandle - Connection pool handle to poll * @returns Promise<number> - 0 for operation not complete, non-zero for complete * @rejects {string} Error message from Go side * * @private */ private _pollConnection; } //# sourceMappingURL=teradata-connection.d.ts.map