### Install Teradata SQL Driver for Python Source: https://context7.com/teradata/python-driver/llms.txt Installs the teradatasql package from PyPI. Supports installation on macOS, Linux, and Windows. Includes commands for initial installation and upgrading to the latest version. ```bash # macOS or Linux pip install teradatasql # Windows py -3 -m pip install teradatasql # Upgrade to latest version pip install --no-cache-dir -U teradatasql ``` -------------------------------- ### Execute Teradata Operations via Command Line Source: https://context7.com/teradata/python-driver/llms.txt Provides examples of using the teradatasql module CLI to check driver versions, test connectivity, and execute SQL queries directly from the terminal. ```bash python -m teradatasql version python -m teradatasql host=myhost,user=myuser,password=mypass python -m teradatasql host=myhost,user=myuser,password=mypass "SELECT * FROM DBC.DBCInfo" python -m teradatasql host=myhost,user=myuser,password=mypass,database=mydb,tmode=ANSI "SELECT CURRENT_DATE" ``` -------------------------------- ### Perform High-Performance FastExport with Teradata Source: https://context7.com/teradata/python-driver/llms.txt Demonstrates how to use FastExport for retrieving large result sets efficiently. Includes examples of processing batches and exporting query results directly to a CSV file. ```python import teradatasql with teradatasql.connect(host="myhost", user="myuser", password="mypass") as con: with con.cursor() as cur: cur.execute("{fn teradata_try_fastexport}SELECT * FROM large_table WHERE status = ?", ["active"]) rows_processed = 0 while True: batch = cur.fetchmany(10000) if not batch: break rows_processed += len(batch) print(f"Exported {rows_processed} rows") cur.execute("{fn teradata_write_csv(/tmp/export_data.csv)}SELECT * FROM sales_data") ``` -------------------------------- ### Python: Handle Teradata Database Errors with Driver Source: https://context7.com/teradata/python-driver/llms.txt Explains how to handle database and driver exceptions using the `teradatasql` exception hierarchy. Shows examples of catching specific errors like `OperationalError` and `DatabaseError`, and ignoring specific error codes during execution. ```python import teradatasql try: with teradatasql.connect(host="myhost", user="myuser", password="mypass") as con: with con.cursor() as cur: cur.execute("SELECT * FROM nonexistent_table") except teradatasql.OperationalError as e: print(f"Operational error: {e}") except teradatasql.DatabaseError as e: print(f"Database error: {e}") except teradatasql.Error as e: print(f"Driver error: {e}") # Ignore specific errors during execution with teradatasql.connect(host="myhost", user="myuser", password="mypass") as con: with con.cursor() as cur: # Ignore error 3807 (object doesn't exist) when dropping cur.execute("DROP TABLE temp_results", ignoreErrors=[3807]) # Ignore multiple error codes cur.execute("CREATE TABLE test (id INT)", ignoreErrors=[3803, 3807]) ``` -------------------------------- ### Python: TERA Mode Undesirable BT/ET Nesting Example Source: https://github.com/teradata/python-driver/blob/master/README.md Demonstrates an example of potentially problematic transaction management in TERA mode when auto-commit is disabled. In this scenario, the driver automatically executes 'BT' before the first SQL request, and explicitly calling 'BT' again leads to nested 'BT' commands, which is generally not recommended for clarity and predictable transaction behavior. ```python # TERA mode example showing undesirable BT/ET nesting con.autocommit = False cur.execute("BT") # BT automatically executed by the driver before this, and produces a nested BT cur.execute("insert into mytable1 values(1, 2)") ``` -------------------------------- ### TERA Mode Transaction Control with Teradata Python Driver Source: https://github.com/teradata/python-driver/blob/master/README.md Illustrates transaction management in TERA mode, where the driver automatically handles 'BT' before statements when autocommit is false. This example shows manual 'ET' for transaction completion. ```python con.autocommit = False cur.execute("insert into mytable1 values(1, 2)") # BT automatically executed by the driver before this cur.execute("insert into mytable2 values(3, 4)") cur.execute("ET") # complete transaction ``` -------------------------------- ### Execute SQL and Fetch Results Source: https://github.com/teradata/python-driver/blob/master/README.md Shows the standard workflow of executing a SQL query and retrieving the results using fetchall(). ```python cursor.execute("SELECT * FROM my_table") results = cursor.fetchall() print(f"Rows affected: {cursor.rowcount}") ``` -------------------------------- ### Connect to Teradata Database using teradatasql Source: https://context7.com/teradata/python-driver/llms.txt Demonstrates how to establish a connection to Teradata Database using the teradatasql.connect function. Supports connection via keyword arguments (kwargs), JSON string, or a combination. Shows how to specify additional parameters like database, transaction mode, SSL mode, and logon mechanism. Emphasizes closing the connection when done. ```python import teradatasql # Connection using kwargs (recommended) con = teradatasql.connect( host="mydbhost.example.com", user="dbuser", password="dbpassword" ) # Connection using JSON string con = teradatasql.connect('{"host":"mydbhost.example.com","user":"dbuser","password":"dbpassword"}') # Connection with additional parameters con = teradatasql.connect( host="mydbhost.example.com", user="dbuser", password="dbpassword", database="mydb", tmode="ANSI", sslmode="REQUIRE", logmech="LDAP" ) # Always close connection when done con.close() ``` -------------------------------- ### GET /connection/attributes Source: https://github.com/teradata/python-driver/blob/master/README.md Retrieves the current connection attributes and metadata for a Teradata session, including TLS, OIDC, and driver-specific configuration settings. ```APIDOC ## GET /connection/attributes ### Description Returns a list of key-value pairs representing the current state and configuration of the active database connection. ### Method GET ### Endpoint /connection/attributes ### Parameters #### Query Parameters - **format** (string) - Optional - The format of the returned attributes (e.g., 'json', 'list'). ### Request Example GET /connection/attributes?format=json ### Response #### Success Response (200) - **ClientConfVersion** (string) - The TLS version determined by the database. - **ClientConfCipherSuite** (string) - The TLS cipher suite in use. - **ClientAttributesEx** (string) - Additional name=value pairs for advanced configuration. - **LM** (string) - The logon authentication method used. - **PYTHON** (string) - The version of the Python interpreter. #### Response Example { "ClientConfVersion": "TLSv1.3", "ClientConfCipherSuite": "TLS_AES_256_GCM_SHA384", "LM": "OIDC", "PYTHON": "3.10.12" } ``` -------------------------------- ### Configure User STARTUP SQL Request Source: https://github.com/teradata/python-driver/blob/master/README.md Demonstrates how to modify a Teradata user to execute a specific SQL command upon session startup. The driver connection parameter 'runstartup' must be set to true for this to take effect. ```sql MODIFY USER susan AS STARTUP='SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL RU' ``` -------------------------------- ### Control Startup SQL Execution and SP Source Saving Source: https://github.com/teradata/python-driver/blob/master/README.md Configures whether the user's `STARTUP` SQL request is executed after logon and whether stored procedure source code is saved in the database upon creation. `runstartup` controls the former, while `sp_spl` controls the latter. ```python connection_string = "DRIVER={Teradata};DBCNAME=your_teradata_host;UID=your_username;PWD=your_password;RUNSTARTUP=true;SP_SPL=false" # Or using keyword arguments: # conn = teradatasql.connect(..., RUNSTARTUP=True, SP_SPL=False) ``` -------------------------------- ### Customize CSV Field Quote Character Source: https://github.com/teradata/python-driver/blob/master/README.md This example demonstrates how to specify a custom field quote character for CSV exports. This customization can be achieved using the connection parameter `field_quote` or the `teradata_field_quote` escape function in the SQL query. ```SQL {fn teradata_field_quote("'")}{fn teradata_write_csv(myFile.csv)}select column1, column2 from my_table ``` -------------------------------- ### Python: Connect with LDAP, Kerberos, TDNEGO, and JWT Authentication Source: https://context7.com/teradata/python-driver/llms.txt Illustrates how to establish connections using different authentication mechanisms: LDAP, Kerberos (KRB5) for Single Sign-On, TDNEGO for automatic GSS-API method selection, and JWT for token-based authentication. ```python import teradatasql # LDAP authentication con_ldap = teradatasql.connect( host="myhost", user="ldap_user", password="ldap_password", logmech="LDAP" ) # Kerberos Single Sign-On (SSO) - no password needed con_krb5 = teradatasql.connect( host="myhost", user="krb_user@REALM.COM", logmech="KRB5" ) # TDNEGO - automatically selects appropriate GSS-API method con_tdnego = teradatasql.connect( host="myhost", user="myuser", password="mypassword", logmech="TDNEGO" ) # JWT authentication con_jwt = teradatasql.connect( host="myhost", logmech="JWT", logdata="token=eyJhbGciOiJSUzI1NiIs..." ) ``` -------------------------------- ### Customize CSV Field Separator Source: https://github.com/teradata/python-driver/blob/master/README.md This example illustrates how to specify a custom field separator character for CSV exports. This can be done either through the connection parameter `field_sep` or using the `teradata_field_sep` escape function within the SQL query. ```SQL {fn teradata_field_sep('|')}{fn teradata_write_csv(myFile.csv)}select column1, column2 from my_table ``` -------------------------------- ### Fetch Query Results with Teradata Python Driver Source: https://context7.com/teradata/python-driver/llms.txt Demonstrates how to retrieve data using fetchone, fetchall, and fetchmany methods. It also shows how to inspect column metadata via the cursor description attribute. ```python import teradatasql with teradatasql.connect(host="myhost", user="myuser", password="mypass") as con: with con.cursor() as cur: cur.execute("SELECT id, name, salary FROM employees ORDER BY id") row = cur.fetchone() while row: print(f"ID: {row[0]}, Name: {row[1]}, Salary: {row[2]}") row = cur.fetchone() cur.execute("SELECT * FROM departments") all_rows = cur.fetchall() cur.execute("SELECT * FROM large_table") cur.arraysize = 100 while True: batch = cur.fetchmany() if not batch: break for row in batch: process(row) cur.execute("SELECT id, name FROM employees") for col in cur.description: print(f"Column: {col[0]}, Type: {col[1]}, Nullable: {col[6]}") ``` -------------------------------- ### teradatasql.connect Source: https://context7.com/teradata/python-driver/llms.txt Establishes a connection to the Teradata Database using host, user, and authentication credentials. ```APIDOC ## teradatasql.connect ### Description Creates a connection to the Teradata Database and returns a Connection object. Parameters can be passed as a JSON string or keyword arguments. ### Method N/A (Python Method) ### Parameters #### Keyword Arguments - **host** (string) - Required - The hostname or IP address of the Teradata server. - **user** (string) - Required - The database username. - **password** (string) - Required - The database password. - **database** (string) - Optional - The default database to connect to. - **tmode** (string) - Optional - Transaction mode (e.g., 'ANSI' or 'TERA'). - **logmech** (string) - Optional - Authentication mechanism (e.g., 'TD2', 'LDAP', 'Kerberos'). ### Request Example import teradatasql con = teradatasql.connect(host="mydbhost.example.com", user="dbuser", password="dbpassword") ``` -------------------------------- ### Connect to Teradata Database Source: https://github.com/teradata/python-driver/blob/master/README.md Demonstrates multiple ways to connect to a Teradata database using the teradatasql.connect function. Parameters can be passed via keyword arguments, a JSON string, or a combination of both. ```python # Using keyword arguments con = teradatasql.connect(host="whomooz", user="guest", password="please") # Using a JSON string con = teradatasql.connect('{"host":"whomooz","user":"guest","password":"please"}') # Using a combination (kwargs take precedence) con = teradatasql.connect('{"host":"whomooz"}', user="guest", password="please") ``` -------------------------------- ### FastLoad Usage with Escape Functions Source: https://github.com/teradata/python-driver/blob/master/README.md Demonstrates how to use FastLoad with different escape functions to control its behavior, including error handling and session management. ```APIDOC ## FastLoad with Escape Functions ### Description This section outlines how to use the FastLoad feature by prepending specific escape functions to your SQL INSERT statements. These functions allow you to control whether FastLoad is required or optional, manage error tables, and govern workload management interactions. ### Method N/A (This describes SQL syntax modifications) ### Endpoint N/A (This describes SQL syntax modifications) ### Parameters N/A ### Request Example ```sql -- Example using teradata_try_fastload INSERT INTO your_table (col1, col2) {fn teradata_try_fastload} VALUES (value1, value2); -- Example using teradata_require_fastload INSERT INTO your_table (col1, col2) {fn teradata_require_fastload} VALUES (value1, value2); -- Example with optional functions INSERT INTO your_table (col1, col2) {fn teradata_sessions(8)} {fn teradata_error_table_1_suffix('_ERR')} {fn teradata_govern_on} {fn teradata_try_fastload} VALUES (value1, value2); ``` ### Response N/A (This describes SQL syntax modifications and driver behavior) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Module Constructors Source: https://github.com/teradata/python-driver/blob/master/README.md Constructors for creating database connections, connection factories, and date/time objects. ```APIDOC ## Module Constructors ### `teradatasql.connect(*JSONConnectionString*, *Parameters...*)` Creates a connection to the database and returns a Connection object. **Parameters:** - `JSONConnectionString` (string): An optional JSON string for connection parameters. Defaults to `None`. - `Parameters...` (kwargs): Optional keyword arguments for connection parameters. **Usage:** Specify connection parameters as a JSON string, as `kwargs`, or a combination. `kwargs` take precedence. ### `teradatasql.factory(*JSONConnectionString*, *Parameters...*)` Creates and returns a connection factory function. Calling this function without arguments yields a Connection object. **Parameters:** - `JSONConnectionString` (string): An optional JSON string for connection parameters. Defaults to `None`. - `Parameters...` (kwargs): Optional keyword arguments for connection parameters. **Usage:** Specify connection parameters as a JSON string, as `kwargs`, or a combination. `kwargs` take precedence. ### `teradatasql.Date(*Year*, *Month*, *Day*)` Creates and returns a `datetime.date` value. ### `teradatasql.DateFromTicks(*Seconds*) Creates and returns a `datetime.date` value from the specified number of seconds after 1970-01-01 00:00:00. ### `teradatasql.Time(*Hour*, *Minute*, *Second*) Creates and returns a `datetime.time` value. ### `teradatasql.TimeFromTicks(*Seconds*) Creates and returns a `datetime.time` value from the specified number of seconds after 1970-01-01 00:00:00. ### `teradatasql.Timestamp(*Year*, *Month*, *Day*, *Hour*, *Minute*, *Second*) Creates and returns a `datetime.datetime` value. ### `teradatasql.TimestampFromTicks(*Seconds*) Creates and returns a `datetime.datetime` value from the specified number of seconds after 1970-01-01 00:00:00. ``` -------------------------------- ### COP Discovery and Load Balancing Source: https://github.com/teradata/python-driver/blob/master/README.md Explains how the Teradata Python Driver handles connections when COP Discovery is enabled or disabled, and how to use alternative load distribution schemes. ```APIDOC ## COP Discovery and Load Balancing ### Description This section describes how the Teradata Python Driver connects to the database, prioritizing COP Discovery but allowing for alternative load balancing methods when COP Discovery is disabled or not configured. ### Connection Behavior - If COP Discovery is turned off, or no COP hostnames are defined in DNS, the driver connects directly to the hostname specified in the `host` connection parameter. - This allows for load distribution schemes other than COP Discovery, such as round-robin DNS or TCP/IP load distribution products. - COP Discovery takes precedence over simple database hostname lookup. ### Configuration To use an alternative load distribution scheme: - Ensure that no COP hostnames are defined in DNS, OR - Turn off COP Discovery by setting the `cop` connection parameter to `false`. ``` -------------------------------- ### Call Stored Procedure Source: https://github.com/teradata/python-driver/blob/master/README.md Demonstrates calling a stored procedure using the callproc method with input parameters. ```python cursor.callproc('my_procedure', [100, 'input_val']) ``` -------------------------------- ### Python: Configure TLS/SSL Connections with Teradata Driver Source: https://context7.com/teradata/python-driver/llms.txt Details how to configure secure TLS/SSL connections, including preferring TLS, requiring TLS with full certificate verification, and requiring TLS with CA verification only. Specifies paths for certificate authorities. ```python import teradatasql # Prefer TLS (default behavior) con = teradatasql.connect( host="myhost", user="myuser", password="mypass", sslmode="PREFER" ) # Require TLS with full certificate verification con = teradatasql.connect( host="myhost", user="myuser", password="mypass", sslmode="VERIFY-FULL", sslca="/path/to/ca-certificates.pem" ) # Require TLS with CA verification only con = teradatasql.connect( host="myhost", user="myuser", password="mypass", sslmode="VERIFY-CA", sslcapath="/path/to/certificates/" ) ``` -------------------------------- ### Connection Configuration Parameters Source: https://github.com/teradata/python-driver/blob/master/README.md Details for configuring session behavior, network settings, and security options for the Teradata Python driver. ```APIDOC ## Connection Configuration Parameters ### Description These parameters are used to configure the behavior of the Teradata Python driver session, including network proxy bypass, session reconnection logic, and security settings. ### Parameters - **proxy_bypass_hosts** (string) - Optional - Pattern for hostnames/addresses to bypass proxy. Default: 'localhost|127.*|[::1]'. - **reconnect_count** (quoted integer) - Optional - Max number of session reconnection attempts. Default: 11. - **reconnect_interval** (quoted integer) - Optional - Seconds to wait between reconnection attempts. Default: 30. - **redrive** (quoted integer) - Optional - Enables session reconnect and automatic SQL request redriving. Values: 0-4. Default: '3'. - **request_timeout** (quoted integer) - Optional - Timeout in seconds for SQL requests. Default: '0' (no timeout). - **runstartup** (quoted boolean) - Optional - Executes user STARTUP SQL after logon. Default: 'false'. - **sessions** (quoted integer) - Optional - Number of data transfer connections for FastLoad/FastExport. - **sip_support** (quoted boolean) - Optional - Controls use of StatementInfo parcel. Default: 'true'. - **sp_spl** (quoted boolean) - Optional - Controls if stored procedure source code is saved. Default: 'true'. - **sslbase64** (string) - Optional - Base64url encoded PEM file contents for CA certificates. ### Request Example { "reconnect_count": "5", "request_timeout": "60", "runstartup": "true" } ``` -------------------------------- ### Module Functions Source: https://github.com/teradata/python-driver/blob/master/README.md Provides access to the command line interface. ```APIDOC ## Module Functions ### `teradatasql.main(*SequenceOfStrings*)` Provides programmatic access to the command line interface. **Parameters:** - `SequenceOfStrings` (list): A sequence of strings representing command-line arguments. ``` -------------------------------- ### Connection Parameters Source: https://github.com/teradata/python-driver/blob/master/README.md This section details the available connection parameters for the Teradata Python driver, explaining their functionality and usage. ```APIDOC ## Connection Parameters ### Description This section details the available connection parameters for the Teradata Python driver, explaining their functionality and usage. ### Parameters #### Request Body Parameters - **govern** (quoted boolean) - Optional - Controls FastLoad and FastExport throttling by Teradata workload management rules. When set to `true` (the default), workload management rules may delay a FastLoad or FastExport. When set to `false`, workload management rules will reject rather than delay a FastLoad or FastExport. Equivalent to the Teradata JDBC Driver `GOVERN` connection parameter. - **host** (string) - Optional - Specifies the database hostname. - **http_proxy** (string) - Optional - Specifies the proxy server URL for HTTP connections to TLS certificate verification CRL and OCSP endpoints. The URL must begin with `http://` and must include a colon `:` and port number. - **http_proxy_password** (string) - Optional - Specifies the proxy server password for the proxy server identified by the `http_proxy` parameter. This parameter may only be specified in conjunction with the `http_proxy` parameter. When this parameter is omitted, no proxy server password is provided to the proxy server identified by the `http_proxy` parameter. - **http_proxy_user** (string) - Optional - Specifies the proxy server username for the proxy server identified by the `http_proxy` parameter. This parameter may only be specified in conjunction with the `http_proxy` parameter. When this parameter is omitted, no proxy server username is provided to the proxy server identified by the `http_proxy` parameter. - **https_port** (quoted integer) - Optional - Specifies the database port number for HTTPS/TLS connections. Equivalent to the Teradata JDBC Driver `HTTPS_PORT` connection parameter. Default: `"443"` - **https_proxy** (string) - Optional - Specifies the proxy server URL for HTTPS/TLS connections to the database and to Identity Provider endpoints. The URL must begin with `http://` and must include a colon `:` and port number. The driver connects to the proxy server using a non-TLS HTTP connection, then uses the HTTP CONNECT method to establish an HTTPS/TLS connection to the destination. Equivalent to the Teradata JDBC Driver `HTTPS_PROXY` connection parameter. - **https_proxy_password** (string) - Optional - Specifies the proxy server password for the proxy server identified by the `https_proxy` parameter. This parameter may only be specified in conjunction with the `https_proxy` parameter. When this parameter is omitted, no proxy server password is provided to the proxy server identified by the `https_proxy` parameter. Equivalent to the Teradata JDBC Driver `HTTPS_PROXY_PASSWORD` connection parameter. - **https_proxy_user** (string) - Optional - Specifies the proxy server username for the proxy server identified by the `https_proxy` parameter. This parameter may only be specified in conjunction with the `https_proxy` parameter. When this parameter is omitted, no proxy server username is provided to the proxy server identified by the `https_proxy` parameter. Equivalent to the Teradata JDBC Driver `HTTPS_PROXY_USER` connection parameter. - **https_retry** (quoted integer) - Optional - Specifies the number of HTTPS connection retries for a single-node database. Specify `0` (zero) to turn off HTTPS connection retries. Equivalent to the Teradata JDBC Driver `HTTPS_RETRY` connection parameter. Default: `"2"` - **jws_algorithm** (string) - Optional - Specifies the JSON Web Signature (JWS) algorithm to sign the JWT Bearer Token for client authentication. Optional when `logmech` is `BEARER` and ignored for other `logmech` values. The default `RS256` is RSASSA-PKCS1-v1_5 using SHA-256. Specify `RS384` for RSASSA-PKCS1-v1_5 using SHA-384. Specify `RS512` for RSASSA-PKCS1-v1_5 using SHA-512. Equivalent to the Teradata JDBC Driver `JWS_ALGORITHM` connection parameter. Default: `"RS256"` ### Request Example ```json { "govern": "true", "host": "your_teradata_host.com", "https_port": "1025", "jws_algorithm": "RS512" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "Connection parameters accepted." } ``` ``` -------------------------------- ### Execute Batch Operations Source: https://github.com/teradata/python-driver/blob/master/README.md Demonstrates using executemany to perform batch inserts or updates using a sequence of parameter sequences. ```python sql = "INSERT INTO my_table (id, val) VALUES (?, ?)" params = [(1, 'a'), (2, 'b'), (3, 'c')] cursor.executemany(sql, params) ``` -------------------------------- ### Configure SSL/TLS and Certificate Handling Source: https://github.com/teradata/python-driver/blob/master/README.md Controls SSL/TLS mode for secure connections and provides a base64url encoded string of CA certificates for verification. The `sslbase64` parameter is used when `sslmode` or `oidc_sslmode` is set to `VERIFY-CA` or `VERIFY-FULL`. ```bash # Example Linux command to generate base64url encoded certificate content: base64 -w0 < cert.pem | tr +/ -_ | tr -d = ``` ```python connection_string = "DRIVER={Teradata};DBCNAME=your_teradata_host;UID=your_username;PWD=your_password;SSLMODE=VERIFY-CA;SSLBASE64=MIIC...your_encoded_cert...END..." # Or using keyword arguments: # conn = teradatasql.connect(..., SSLMODE='VERIFY-CA', SSLBASE64='MIIC...your_encoded_cert...END...') ``` -------------------------------- ### General Connection Parameters Source: https://github.com/teradata/python-driver/blob/master/README.md Parameters for controlling data type handling and transaction modes. ```APIDOC ## General Connection Parameters ### Description Parameters for controlling data type handling and transaction modes. ### Parameters #### Query Parameters - **teradata_values** (quoted boolean) - Optional - Controls whether `str` or a more specific Python data type is used for certain result set column value types. - **tmode** (string) - Optional - Specifies the transaction mode. Possible values are `DEFAULT`, `ANSI`, or `TERA`. ### Request Example ```json { "tmode": "ANSI", "teradata_values": "false" } ``` ### Response #### Success Response (200) - **message** (string) - Status of parameter update #### Response Example ```json { "message": "Parameters updated successfully" } ``` ``` -------------------------------- ### Python: Call Stored Procedures with Teradata Driver Source: https://context7.com/teradata/python-driver/llms.txt Shows how to call stored procedures using both the `callproc` method and the `CALL` escape syntax. Supports IN, INOUT parameters, fetching results, and creating stored procedures. ```python import teradatasql with teradatasql.connect(host="myhost", user="myuser", password="mypass") as con: with con.cursor() as cur: # Call stored procedure using callproc cur.callproc("my_procedure", [param1_value, param2_value]) # Fetch INOUT parameter results and dynamic result sets result = cur.fetchone() # INOUT parameter values while cur.nextset(): rows = cur.fetchall() # Dynamic result set for row in rows: print(row) # Call using escape syntax cur.execute("{call my_procedure(?, ?)}", [input_val1, input_val2]) # Create a stored procedure cur.execute(""" REPLACE PROCEDURE get_employee_count(IN dept VARCHAR(50), OUT emp_count INTEGER) BEGIN SELECT COUNT(*) INTO emp_count FROM employees WHERE department = dept; END; """) ``` -------------------------------- ### Configure Cursor Fetch Size Source: https://github.com/teradata/python-driver/blob/master/README.md Demonstrates how to set the arraysize attribute of a cursor to control the number of rows fetched by fetchmany() in a single operation. ```python cursor.arraysize = 100 rows = cursor.fetchmany() ``` -------------------------------- ### Connection Methods Source: https://github.com/teradata/python-driver/blob/master/README.md Methods available on a Connection object for transaction management, cursor creation, and query execution. ```APIDOC ## Connection Methods ### `.cancel()` Attempts to cancel the currently executing SQL request. Does nothing if no request is executing. Must be called from a different thread than the one executing the request. ### `.close()` Closes the Connection. ### `.commit()` Commits the current transaction. ### `.cursor()` Creates and returns a new Cursor object for the Connection. ### `.nativeSQL(*SQLRequest*)` Returns the specified SQL request text after conversion to native Teradata SQL. **Parameters:** - `SQLRequest` (string): The SQL query string. **Note:** The `{fn teradata_nativesql}` escape clause is automatically prepended. ### `.rollback()` Rolls back the current transaction. ``` -------------------------------- ### Execute SQL Queries with teradatasql Cursor Source: https://context7.com/teradata/python-driver/llms.txt Shows how to execute SQL statements using the cursor object obtained from a Teradata connection. Supports simple queries, parameterized queries with bind values (using '?'), and inserting data with parameters. Also demonstrates ignoring specific error codes during execution. ```python import teradatasql with teradatasql.connect(host="myhost", user="myuser", password="mypass") as con: with con.cursor() as cur: # Simple query cur.execute("SELECT * FROM DBC.DBCInfo") rows = cur.fetchall() for row in rows: print(row) # Parameterized query with bind values cur.execute("SELECT * FROM employees WHERE department = ? AND salary > ?", ["Engineering", 50000]) # Insert with parameters cur.execute("INSERT INTO products (name, price) VALUES (?, ?)", ["Widget", 29.99]) # Ignore specific error codes cur.execute("DROP TABLE temp_table", ignoreErrors=[3807]) # Ignore "table doesn't exist" ``` -------------------------------- ### Retrieve Connection Metadata using Escape Functions Source: https://context7.com/teradata/python-driver/llms.txt Demonstrates how to use Teradata-specific escape functions to retrieve driver version, database version, session details, and connection status without additional round-trips. ```python import teradatasql with teradatasql.connect(host="myhost", user="myuser", password="mypass") as con: with con.cursor() as cur: cur.execute("{fn teradata_nativesql}{fn teradata_driver_version}") print(f"Driver version: {cur.fetchone()[0]}") cur.execute("{fn teradata_nativesql}{fn teradata_database_version}") print(f"Database version: {cur.fetchone()[0]}") cur.execute("{fn teradata_nativesql}{fn teradata_session_number}") print(f"Session number: {cur.fetchone()[0]}") cur.execute("{fn teradata_nativesql}{fn teradata_provide(transaction_mode)}") print(f"Transaction mode: {cur.fetchone()[0]}") cur.execute("{fn teradata_nativesql}{fn teradata_connected}") print(f"Connected: {cur.fetchone()[0]}") ``` -------------------------------- ### SSL/TLS Connection Parameters Source: https://github.com/teradata/python-driver/blob/master/README.md Parameters related to configuring Secure Sockets Layer (SSL) and Transport Layer Security (TLS) for secure connections to the database. ```APIDOC ## SSL/TLS Connection Parameters ### Description Parameters for configuring secure connections using SSL/TLS. ### Parameters #### Query Parameters - **sslca** (string) - Optional - Specifies the file name of a PEM file that contains Certificate Authority (CA) certificates for use with `sslmode` or `oidc_sslmode` values `VERIFY-CA` or `VERIFY-FULL`. Equivalent to the Teradata JDBC Driver `SSLCA` connection parameter. - **sslcapath** (string) - Optional - Specifies a directory of PEM files that contain Certificate Authority (CA) certificates for use with `sslmode` or `oidc_sslmode` values `VERIFY-CA` or `VERIFY-FULL`. Only files with an extension of `.pem` are used. - **sslcipher** (string) - Optional - Specifies the TLS cipher for HTTPS/TLS connections. Default lets database and driver choose the most appropriate TLS cipher. Omitting this parameter is recommended. Use this parameter only for troubleshooting TLS handshake issues. - **sslcrc** (string) - Optional - Controls TLS certificate revocation checking (CRC) for HTTPS/TLS connections. Values are case-insensitive. `ALLOW` performs CRC for `VERIFY-CA` and `VERIFY-FULL`, and provides soft fail CRC. `PREFER` performs CRC for all HTTPS connections, and provides soft fail CRC. `REQUIRE` performs CRC for all HTTPS connections, and requires CRC for `VERIFY-CA` and `VERIFY-FULL`. - **sslcrl** (quoted boolean) - Optional - Controls the use of Certificate Revocation List (CRL) for TLS certificate revocation checking for HTTPS/TLS connections. OCSP is preferred over CRL. - **sslmode** (string) - Optional - Specifies the mode for connections to the database. Values are case-insensitive. `DISABLE` disables HTTPS/TLS. `ALLOW` uses non-TLS unless required. `PREFER` uses HTTPS/TLS unless not offered. `REQUIRE` uses only HTTPS/TLS. `VERIFY-CA` uses only HTTPS/TLS and verifies CA. `VERIFY-FULL` uses only HTTPS/TLS, verifies CA, and verifies hostname. - **sslnamedgroups** (string) - Optional - Specifies the TLS key exchange named groups for HTTPS/TLS connections. Multiple named groups are separated by commas. Default lets database and driver choose the most appropriate named group. Omitting this parameter is recommended. - **sslocsp** (quoted boolean) - Optional - Controls the use of Online Certificate Status Protocol (OCSP) for TLS certificate revocation checking for HTTPS/TLS connections. - **sslprotocol** (string) - Optional - Specifies the TLS protocol for HTTPS/TLS connections. Omitting this parameter is recommended. Use this parameter only for troubleshooting TLS handshake issues. ### Request Example ```json { "sslmode": "VERIFY-FULL", "sslca": "/path/to/ca.pem" } ``` ### Response #### Success Response (200) - **message** (string) - Connection status #### Response Example ```json { "message": "Connection successful" } ``` ``` -------------------------------- ### Logon Authentication Methods Source: https://github.com/teradata/python-driver/blob/master/README.md This section describes the different logon authentication methods that can be selected using the `logmech` connection parameter in the Teradata Python driver. ```APIDOC ## Logon Authentication Methods This section describes the logon authentication methods selected by the `logmech` connection parameter. ### BEARER **Description**: OIDC Client Credentials Grant with JWT Bearer Token for client authentication. **Usage and Requirements**: Intended for automated logon by service accounts. `user`, `password`, `logdata`, and `oauth_scopes` must be omitted. `jws_private_key` is required. `jws_cert` is needed for Identity Providers requiring an "x5t" header thumbprint. `oidc_clientid` can override the default Client ID. `oidc_claim`, `oidc_scope`, `oidc_token`, and `jws_algorithm` are optional. The database user must have the "logon with null password" permission. The database must be configured with Identity Provider information for Federated Authentication. ### BROWSER **Description**: Browser Authentication, also known as OIDC Authorization Code Flow with Proof Key for Code Exchange (PKCE). **Usage and Requirements**: Intended for interactive logon by individual users. `password` and `logdata` must be omitted. `user` is optional and used as the OIDC login hint and token cache key. `browser`, `browser_tab_timeout`, `browser_timeout`, `oauth_scopes`, `oidc_claim`, `oidc_clientid`, `oidc_prompt`, `oidc_scope`, and `oidc_token` are optional. Supported on Windows and macOS. The database user must have the "logon with null password" permission. The database must be configured with Identity Provider information for Federated Authentication. ### CODE **Description**: OIDC Device Code Flow, also known as OIDC Device Authorization Grant. **Usage and Requirements**: Intended for interactive logon by individual users. `password` and `logdata` must be omitted. `user` is optional and used as the OIDC login hint and token cache key. `code_append_file`, `oauth_scopes`, `oidc_claim`, `oidc_clientid`, `oidc_scope`, and `oidc_token` are optional. The database user must have the "logon with null password" permission. The database must be configured with Identity Provider information for Federated Authentication. ### CRED **Description**: OIDC Client Credentials Grant with client_secret_post for client authentication. **Usage and Requirements**: Intended for automated logon by service accounts. `user`, `password`, `oauth_scopes`, `oidc_clientid`, and `oidc_scope` must be omitted. `logdata` must contain the Client Credentials Grant request HTTP POST Form Data encoded as Content-Type application/x-www-form-urlencoded. `oidc_claim` and `oidc_token` are optional. The database user must have the "logon with null password" permission. The database must be configured with Identity Provider information for Federated Authentication. ### JWT **Description**: JSON Web Token (JWT). **Usage and Requirements**: `logdata` must contain `token=` followed by the JSON Web Token. The database user must have the "logon with null password" permission. Your application must obtain a valid JWT from an Identity Provider. The database must be configured to trust JWTs issued by your Identity Provider. ### KRB5 **Description**: GSS-API Kerberos V5. **Usage and Requirements**: Requires significant administration tasks on the machine running the driver. For Kerberos Single Sign On (SSO), the database user must have the "logon with null password" permission. ### LDAP **Description**: GSS-API Lightweight Directory Access Protocol (LDAP). **Usage and Requirements**: Requires significant administration effort to set up the LDAP environment. Once complete, LDAP can be used without additional work on the machine running the driver. ``` -------------------------------- ### Python: Read and Write CSV Files with Teradata Driver Source: https://context7.com/teradata/python-driver/llms.txt Demonstrates reading data from CSV files for batch inserts and exporting query results to CSV files. Supports custom field separators and quote characters, and exporting multiple result sets. ```python import teradatasql with teradatasql.connect(host="myhost", user="myuser", password="mypass") as con: with con.cursor() as cur: # Import data from CSV file cur.execute( "{fn teradata_read_csv(/path/to/data.csv)}INSERT INTO target_table (col1, col2, col3) VALUES (?, ?, ?)" ) # Export query results to CSV cur.execute( "{fn teradata_write_csv(/path/to/output.csv)}SELECT * FROM source_table" ) # Export with custom field separator and quote character cur.execute( "{fn teradata_field_sep('|')}{fn teradata_field_quote("'")}" "{fn teradata_write_csv(/path/to/output.csv)}SELECT * FROM source_table" ) # Export multiple result sets (creates output.csv, output_1.csv) cur.execute( "{fn teradata_write_csv(/path/to/output.csv)}SELECT * FROM table1 ; SELECT * FROM table2" ) ``` -------------------------------- ### Stored Procedure Calls Source: https://github.com/teradata/python-driver/blob/master/README.md Syntax for invoking stored procedures. ```APIDOC ## {call ProcedureName} ### Description Invokes a stored procedure on the Teradata database. ### Syntax `{call ProcedureName(param1, param2)}` ``` -------------------------------- ### Execute SQL Statements with Teradata Python Driver Source: https://github.com/teradata/python-driver/blob/master/README.md Demonstrates executing raw SQL INSERT statements using the Teradata Python driver's cursor object. It shows basic execution and the use of 'ET' for transaction control, though not recommended for complex scenarios. ```python cur.execute("insert into mytable2 values(3, 4)") cur.execute("ET") # unwind nesting cur.execute("ET") # complete transaction ``` -------------------------------- ### Configure Proxy Bypass Hosts Source: https://github.com/teradata/python-driver/blob/master/README.md Specifies a pattern for hostnames and addresses to bypass the proxy server. This parameter requires `http_proxy` or `https_proxy` to be set. Multiple entries are separated by '|', and '*' can be used as a wildcard. Defaults to bypassing loopback addresses if omitted. ```python connection_string = "DRIVER={Teradata};DBCNAME=your_teradata_host;UID=your_username;PWD=your_password;PROXY_BYPASS_HOSTS=localhost|192.168.*|*.example.com" # Or using keyword arguments: # conn = teradatasql.connect(..., PROXY_BYPASS_HOSTS="localhost|192.168.*|*.example.com") ``` -------------------------------- ### POST /sql/batch-insert-csv Source: https://github.com/teradata/python-driver/blob/master/README.md Executes a batch insert operation using data provided in a CSV file. ```APIDOC ## POST /sql/batch-insert-csv ### Description Executes a SQL batch insert or FastLoad operation by reading bind values from a specified CSV file. ### Method POST ### Endpoint {fn teradata_read_csv(CSVFileName)} INSERT INTO table_name (col1, col2) VALUES (?, ?) ### Parameters #### Path Parameters - **CSVFileName** (string) - Required - The path to the CSV file containing the batch data. #### Request Body - **SQL Statement** (string) - Required - The INSERT statement prepended with the teradata_read_csv escape function. ### Request Example {fn teradata_read_csv('data.csv')} INSERT INTO my_table (id, name) VALUES (?, ?) ### Response #### Success Response (200) - **Status** (string) - Indicates successful processing of the batch insert. #### Response Example { "status": "success", "records_inserted": 100 } ``` -------------------------------- ### Teradata Python Driver: BINARY Type Object Source: https://github.com/teradata/python-driver/blob/master/README.md Demonstrates how to use the teradatasql.BINARY type object to identify SQL BLOB, BYTE, or VARBYTE columns. This is useful when comparing with the Cursor's description attribute. ```python '.description[Column][1] == teradatasql.BINARY' ``` -------------------------------- ### Executing Teradata Connection Escape Clauses Source: https://github.com/teradata/python-driver/blob/master/README.md Demonstrates how to use the native SQL escape clause syntax within a Teradata database query. These functions return metadata about the current session or driver configuration. ```sql SELECT {fn teradata_amp_count} AS amp_count, {fn teradata_driver_version} AS driver_version; ``` ```sql SELECT {fn teradata_provide(connection_id)} AS conn_id, {fn teradata_provide(transaction_mode)} AS mode; ``` -------------------------------- ### Configure Session Reconnect Behavior Source: https://github.com/teradata/python-driver/blob/master/README.md Enables session reconnect functionality and sets the maximum number of reconnection attempts and the interval between attempts. If omitted but session reconnect is enabled, defaults to 11 attempts and 30 seconds interval. The `redrive` parameter further controls automatic redriving of interrupted SQL requests. ```python connection_string = "DRIVER={Teradata};DBCNAME=your_teradata_host;UID=your_username;PWD=your_password;RECONNECT_COUNT=5;RECONNECT_INTERVAL=60;REDrive=4" # Or using keyword arguments: # conn = teradatasql.connect(..., RECONNECT_COUNT=5, RECONNECT_INTERVAL=60, REDrive=4) ``` -------------------------------- ### Teradata FastExport/FastLoad Attempt Source: https://github.com/teradata/python-driver/blob/master/README.md These functions attempt to use FastExport or FastLoad for the SQL request. If the utility is not available or suitable, the request may fall back to a different method. ```SQL {fn teradata_try_fastexport} ``` ```SQL {fn teradata_try_fastload} ``` -------------------------------- ### Import Teradata SQL Driver Source: https://github.com/teradata/python-driver/blob/master/README.md The fundamental step to using the Teradata driver is importing the teradatasql package into your Python script. ```python import teradatasql ``` -------------------------------- ### Conversion Functions Source: https://github.com/teradata/python-driver/blob/master/README.md Describes the syntax for using conversion functions to cast values into specific SQL data types. ```APIDOC ## {fn CONVERT(value, type)} ### Description Converts a value to a specified SQL data type before transmission. ### Syntax `{fn CONVERT(value, SQL_TYPE)}` ### Supported Types - SQL_BIGINT - SQL_CHAR(size) - SQL_DATE - SQL_INTEGER - SQL_VARCHAR(size) - (And others as listed in the driver documentation) ``` -------------------------------- ### Handling NULL values with teradata_parameter Source: https://github.com/teradata/python-driver/blob/master/README.md Demonstrates how to explicitly specify a data type for a NULL parameter using the teradata_parameter escape function to prevent database error 3532. ```python cur.execute("{fn teradata_parameter(1, BYTE(4))}update mytable set bytecolumn = ?", [None]) ``` -------------------------------- ### Obtaining FastLoad Warnings and Errors Source: https://github.com/teradata/python-driver/blob/master/README.md Details how to retrieve warning and error information generated by FastLoad after each batch of rows is inserted. ```APIDOC ## Obtaining FastLoad Warnings and Errors ### Description This section describes how to retrieve warning and error messages generated by the FastLoad process after each batch of rows is processed. This is crucial for identifying and handling data errors. ### Method N/A (This describes SQL syntax modifications) ### Endpoint N/A (This describes SQL syntax modifications) ### Parameters N/A ### Request Example ```sql -- Retrieve warnings generated by FastLoad SELECT {fn teradata_nativesql}{fn teradata_get_warnings} ``` ### Response N/A (This describes SQL syntax modifications and driver behavior) #### Success Response (200) - **Warnings** (string) - A string containing all warnings generated by FastLoad for the preceding request. This can include constraint violations or unique primary index violations. #### Response Example ```json { "Warnings": "Warning: Duplicate row found for primary index. Row skipped." } ``` ``` -------------------------------- ### Module Globals Source: https://github.com/teradata/python-driver/blob/master/README.md Global attributes providing information about the driver version, API level, thread safety, and parameter style. ```APIDOC ## Module Globals ### `teradatasql.__version__` The package version number (string). ### `teradatasql.apilevel` String constant `"2.0"` indicating implementation of PEP-249 Python Database API Specification 2.0. ### `teradatasql.threadsafety` Integer constant `2` indicating that threads may share this module and connections, but not cursors. ### `teradatasql.paramstyle` String constant `"qmark"` indicating that prepared SQL requests use question-mark parameter markers. ```