Metadata-Version: 2.1
Name: huawei-aura-connectorapi
Version: 3.9.0
Summary: Aura Python Connector API
Home-page: https://codehub-g.huawei.com/cbu/ei/dws/fabric/PythonSDK/home
Author: aura
Author-email: 
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8,<4.0
Description-Content-Type: text/markdown
Requires-Dist: esdk-obs-python >=3.23.12
Requires-Dist: requests >=2.32.3
Requires-Dist: orjson >=3.10.15
Requires-Dist: six >=1.17.0
Requires-Dist: zstd >=1.5.6.4
Requires-Dist: pyarrow >=16.1.0
Requires-Dist: pandas >=2.0.3
Requires-Dist: python-dateutil >=2.8.2

# English Version

# Aura Python Connector API
*This document describes the code and usage of the Connector API of the Python version of Aura.*
## Code structure：
- aura:Code file
- pytest_template:Unit Test Cases
## Dependency library：
- orjson
- requests
- esdk-obs-python
- six
- zstd
- pandas
- python-dateutil
- pyarrow

*Note: The above dependency libraries will be automatically installed when installing this Connector API. If the installation fails, please install them manually.*
## Python Connector API interface overview
| Interface Name         | Function                                        | Description                            |
|-------------|-------------------------------------------|---------------------------------|
| Create session   | AuraClient.createSession             | Creates a session and returns the session ID and status.                |
| Query session status | AuraClient.getSessionStatus          | Queries the status of a specified session.                |
| Close session   | AuraClient.closeSession              | Close a specified session, no body is returned.              |
| Send query request      | AuraClient.executeQuery              | Sending SQL queries asynchronously.                         |
| Query request result      | AuraClient.getSummary                | Obtain the query result.                     |
| Obtain Result Set       | AuraClient.getStatementResult        | Obtains the result set of the specified number of pages in the current query.             |
| Cancel Query Request      | AuraClient.cancelExecute             | Cancel an asynchronous request in execution.                    |

In addition, the Aura Python Connector API supports the invoking mode that complies with the PEP249 standard. The interface method is as follows:
## PEP249 Standard Interfaces overview
| Interface Name         | Function                                        | Description                                                                              |
|------------------------|----------------------------|------------------------------------------------------------------------------------------|
| create a connection    | AuraConnector.connect | Creates a connection and returns the connection object.                                  |
| create a cursor        | Connection.cursor          | Creates a cursor and returns the cursor object.                                          |
| Executing an SQL query | CursorObject.execute       | Executing an SQL Query Using a Cursor.                                                   |
| Return the next tuple  | CursorObject.fetchone      | Obtain the next tuple of the query result.                                               |
| Return the remaining tuples                 | CursorObject.fetchall      | Obtain all the remaining tuples of the query result.                                     |
| Switch to the next result set                | CursorObject.nextset       | witch to the next result set and discard the remaining tuples in the current result set. |

## Description of the request body：
### `SessionRequest`
#### Request body for creating a session
#### Parameter Description：
| Parameter Name                      | Parameter Type | Mandatory Parameter | Description                                                                                                                                                                                   | 
|---------------------------|------|------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| endpoint_id               | str  | Yes   | User's job endpoint ID.                                                                                                                                                                       |
| instance_id | str  | Yes   | LakeFormation instance ID.                                                                                                                                                                    |
| catalog_name              | str  | Yes   | LakeFormation catalog name.                                                                                                                                                                   |
| wait_timeout | str  | No   | Create session queue waiting time, in seconds, with a value range of [300, 7200]. If a value is provided, it will be created asynchronously; if not filled, it will be created synchronously. |

### `QueryRequest`
#### Request body for sending query
#### Parameter Description：
| Parameter Name                      | Parameter Type | Mandatory Parameter | Description                                                           | 
|---------------------------|-----------------|------|-----------------|
| statement | str             | Yes   | SQL query statement.        |
| session_id              | str             | Yes   | Used session ID.           |
| limit              | int             | No   | Limit the number of rows returned.    |
| bindings              | list[list[str]] | No   | List of bound parameters.           |

## Description of the response body：：
### `SessionResponse`
#### Information about a created session.
#### Parameter Description：
| Parameter Name                      | Parameter Type |  Description    |
|------|------|----------------|
|session_id|str| The ID of the session. |
|status|str| The status of the session.   |

Value of status：

| Value | Description |
|-----|----|
| RUNNING | The current session is running. |
| CLOSED | The current session has been closed. |
| WAITING | The current session is waiting to be created in a queue.|
|CREATING | The current session is being created.|
|FAIL|Failed to create the current session.|

### `QueryResponse`
#### Information about SQL query response
#### Parameter Description：
| Parameter Name                      | Parameter Type |  Description    |
|--------------|--------------------------|------------|
| status       | int                      | Execution status of the current query. |
| session_id   | str                      | Used session ID.      |
| statement_id | str                      | the ID of the query statement.      |

### `StatementSet`
#### Information about the current query
#### Parameter Description：
| Parameter Name                      | Parameter Type |  Description    | 
|--------------|-----------------|----------------|
| status       | str             | Execution status of the current query.     |
| statements   | List[Statement] | Statement execution information contained in the current execution. |
*Note: When the SQL request is not executed, statements are an empty list. Otherwise, information about each statement is included.*


Value of status：

| Value | Description |
|----------|-------|
| FAIL     | Failed to execute the statement.  |
| SUCCESSFUL   | Execution succeeded.  |
| RUNNING  | The statements are being executed.   |
| EMPTY | The statement result set is empty. |
| WAITING     | The current statements are queued for execution.   |

### `Statement`
#### Execution information of a single statement
#### Parameter Description：
| Parameter Name                      | Parameter Type |  Description    | 
|--------------|--------------|--------------|
| status       | str          | Execution status of the SQL statement.  |
| statement_id | str          | the ID of the current statement.        |
| session_id   | str          | the session ID that executes the statement.  |
| num_rows     | int          | Total number of rows in the result set.       |
| row_count    | int          | Number of rows in the result set on the current page.       |
| page_count   | int          | Total number of pages in the result set.        |
| page_no      | int          | Number of pages in the current result set, starting from 1. |
| err_code     | int          | Error code.         |
| sql_state    | int          | SQL status code.      |
| message      | str          | Information of error.     |
| schema       | List[Column] | Information of schema in the result set. |

Value of status：

| Value | Description |
|-----|---------------------|
| PGRES_COMMAND_OK  | This statement is a command that does not return data.       |
| PGRES_TUPLES_OK   | The statement contains rows of data.           |
| PGRES_FATAL_ERROR   | Failed to execute the query.      |

### `Result`
#### Result set information for the statement
#### Parameter Description：
| Parameter Name                      | Parameter Type |  Description    | 
|--------------|-----------|--------------|
| status       | str       | Execution status of the SQL statement.  |
| statement_id | str       | the ID of the current statement.        |
| num_rows     | int       | Total number of rows in the result set.       |
| row_count    | int       | Number of rows in the result set on the current page.       |
| page_count   | int       | Total number of pages in the result set.         |
| page_no      | int       | Number of pages in the current result set, starting from 1. |
| err_code     | int       | Error code.          |
| sql_state      | int       | SQL status code.      |
| message      | str       | Information of error.        |
| result_set   | ResultSet | Result set in JSON format.   |
| arrow_batch | RecordBatch | Result set in ARROW format.|   

Parameter list of ResultSet：

| Parameter Name                      | Parameter Type |  Description    | 
|--------------|--------------|------------|
| columns      | list[Column] | The data list of columns.      |
| rows         | list[list[str]]    | The data of rows.       |   

Parameter list of Column：

| Parameter Name                      | Parameter Type |  Description    | 
|----------|------|--------|
| name     | str  | The name of the column.  |
| table_id | int  | The ID of the table.  |
| colunm_id | int  |The ID of the column.  |
| format   | int  | Data format of the column.    |
| type     | int  | Data type of the column.    |
| size     | int  |   The size of type.  |
| typemod  | int  | Type-specific modifier info. |


Value of status：

| Value | Description |
|-----|---------------------|
| -1  | Execution failed.       |
| 0   | Execution succeeded.   |
| 1   | The query is being executed.      |
| 2   | The statement does not contain a result set. |
| 3   | Queuing for execution.  |

## The Description of methods：
### Initialize the Client
```python
def AuraClient(endpoint, accessKey, secretKey, securityToken=None, proxies=None, verify=False)
```
#### Enter the user authentication information to initialize the client
#### The Description of parameters:

| Parameter Name          | Parameter Type | Mandatory Parameter        | Description                                                                            | 
|---------------|------|-------------|--------------------------------------------------------------------------------|
| endpoint      | str  | Yes          | Specify the service area，For details about how to query service regions, see [Regions and Endpoints](https://console.huaweicloud.com/apiexplorer/#/endpoint)。 |
| accessKey     | str  | Yes          | Access key ID.                                                                     | 
| secretKey     | str  | Yes          | Security access key。                                                                         | 
| securityToken | str  | No          | Temporary authentication token, which is required when a temporary AK/SK is used.                                                                |
| token     | str  | No          | IAM user Token.                                                                         | 
| proxies       | dict | No          | Indicates whether to use a proxy. If this parameter is left blank, the system proxy is used by default.                                                          |
| verify        | bool | No, The default value is False. | Indicates whether to verify the SSL certificate of the server.                                                                |
*Note：<br>1）If you provide a permanent AK and SK, you do not need to enter securityToken. If you use a temporary AK and SK, you must enter securityToken. For details, see[Obtaining a Temporary AK/SK](https://support.huaweicloud.com/usermanual-ca/ca_01_0003.html)。<br>2）The IAM token is optional. If a user provides an IAM token, the token is preferentially used to access Aura API. Otherwise, the access key is used to access Aura API.For details about how to obtain a token, see [Obtaining an IAM User Token] (https://support.huaweicloud.com/api-iam/iam_30_0001.html).*
#### Return: AuraClient client instance

### Create session
```python
def createSession(workspaceId, request, timeout=None)
```
#### Create a session and return the infomation
#### The Description of parameters：
| Parameter Name          | Parameter Type | Mandatory Parameter        | Description                                                                            |
|---------------------------|----------------|------|----------------------|
| workspaceId | str            | Yes   | Specifies the ID of the aura workspace created by the user. |
| request                      | sessionRequest | Yes   | The request body of session.         |
| timeout | float            | No   | Request timeout interval.              |
#### Return：Session instance response class `SessionResponse`

### Query the status of session
```python
def getSessionStatus(workspaceId, sessionId, timeout=None)
```
#### Querying the Status of a Specified Session
#### The Description of parameters：
| Parameter Name          | Parameter Type | Mandatory Parameter        | Description           |
|-------------|-------|------|----------------------|
| workspaceId | str   | Yes   | Specifies the ID of the aura workspace created by the user. |
| sessionId   | str   | Yes   | Specifies the ID of the session to be queried.     |
| timeout     | float | No   | Request timeout interval.              |
#### Return：the string of the session status

Session status value：

| Value | Description |
|-----|----|
| RUNNING | The session is running. |
| CLOSED | The session has been closed. |
| WAITING | The session is waiting to be created.|
|CREATING | The session is being created.|
|FAIL|Failed to create the session.|

### Close a session
```python
def closeSession(workspaceId, sessionId, timeout=None)
```
#### Close a specified session
#### The Description of parameters：
| Parameter Name          | Parameter Type | Mandatory Parameter        | Description           | 
|-------------|---------------------|------|----------------------|
| workspaceId | str                 | Yes   | Specifies the ID of the aura workspace created by the user. |
| sessionId   | str | Yes   | Specify the ID of the session to be closed.     |
| timeout     | float                | No   | Request timeout interval.              |
#### Return：Empty response body

### Send and execute an SQL query
```python
def executeQuery(workspaceId, request, timeout=None)
```
#### Send Query request
#### The Description of parameters：
| Parameter Name          | Parameter Type | Mandatory Parameter        | Description           |
|---------------------------|--------------|------|----------------------|
| workspaceId | str          | Yes   | Specifies the ID of the aura workspace created by the user. |
| request                      | QueryRequest | Yes   | The request body of SQL query.              |
| timeout | int          | No   | Request timeout interval.              |
#### Return：SQL request response class `QueryResponse`


### Query the summary of an SQL
```python
def getSummary(workspaceId, query_resp, get_schema=True, timeout=None)
```
#### Query the execution results of this request, including information for each individual statement.
#### The Description of parameters：
| Parameter Name          | Parameter Type | Mandatory Parameter        | Description           | 
|---------------------------|---------------|------|---------------------------|
| workspaceId | str           | Yes   | Specifies the ID of the aura workspace created by the user.      |
| query_resp                     | QueryResponse | Yes   | The response of query request.                  |
| get_schema                    | bool          | No   | Whether to return the schema information of the query table, default is True. |
| timeout | float         | No   | Request timeout interval.                   |
#### Return：`StatementSet`

### Obtain the result set of query
```python
def getStatementResult(statement, page_num=1, from_obs: bool = True, convert_type: bool = False, workspaceId=None, timeout=None)
```
#### Query SQL request result
#### The Description of parameters：
| Parameter Name          | Parameter Type | Mandatory Parameter  | Description           | 
|-------------|-----------|----------------------|--------------------------------------------|
| statement   | Statement | Yes                  | Information about the query statement.                                  |
| page_num    | int       | Yes                  | The default value is 1, indicating the specified number of pages in the query result set. When the specified number of pages exceeds the total number of pages in the query result set, an empty result set is returned. |
| from_obs | bool | No, default is True  | Specifies whether to directly retrieve the result set from OBS. |
|convert_type|bool| No, default is False |Specify whether to convert to the corresponding Python data type based on the data type OID.|
| workspaceId | str | No                   | The ID of the workspace created by the user in Aura. This parameter is required when from_obs is False. |
| timeout     | float       | No                   | Request timeout interval.                                    |
#### Return：Result Set Class`Result`
*Note: The default HTTPS timeout interval of OBS SDK is 60s and timeout cannot be set to None. Therefore, when you set timeout to None, the OBS timeout interval is set to the default value.*

### Cancel an SQL query
```python
def cancelExecute(self, workspaceId, response, timeout=None)
```
#### Cancel an SQL query request
#### The Description of parameters：
| Parameter Name          | Parameter Type | Mandatory Parameter        | Description           | 
|-------------|------|------|---------------------|
| workspaceId | str                 | Yes   | Specifies the ID of the aura workspace created by the user. |
| response   | QueryResponse  | Yes   | ID of the session for sending a request.     |
| timeout     | float                 | No   | Request timeout interval.              |
#### Return：Empty response body

## The description of PEP249 standard interfaces
### Create a connection: AuraConnector.connect
```python
def connect(endpoint: str,
            workspaceId: str,
            request: SessionRequest,
            accessKey: str,
            secretKey: str,
            token: str = None,
            securityToken: str = None,
            timeout: float = None,
            proxies: dict = None,
            verify: bool = False,
            concurrent_max_worker: int = 1,
            from_obs: bool = True
)
```
#### The Description of parameters：
| Parameter Name          | Parameter Type | Mandatory Parameter                   | Description           | 
|-------------|----------------|---------------------------------------|-------------------------------------------------------------------------------|
| endpoint | str | Yes                                   | Specifies the region of the service. Query the region and endpoint. [Region and endpoint](https://console.huaweicloud.com/apiexplorer/#/endpoint). |
| workspaceId | str | Yes                                   | Workspace ID of an aura created by a user. |
| request | sessionRequest | Yes                                   | Session request information. |
| accessKey | str | Yes                                   | Access key ID. |
| secretKey | str | Yes                                   | Secure access key. |
| token | str | No                                    | IAM user token. |
| securityToken | str | No                              | Required when a temporary AK/SK is used. |
| timeout | float | No                              | Request timeout interval. |
| proxies | dict | No                              | Indicates whether to use a proxy. If this parameter is left blank, the system proxy is used by default. |
| verify | bool | No. The default value is False. | Indicates whether to verify the SSL certificate of the server. |
| concurrent_max_worker | int | No. The default value is 1.     | Control the number of concurrent pages for obtaining result sets. |
| from_obs | bool | No, default is True | Specifies whether to directly retrieve the result set from OBS. |
#### Return: connection object Connection

### Create a cursor: Connection.cursor
```python
def cursor()
```
#### Return: cursor object CursorObject

### Execute SQL query: CursorObject.execute
```python
def execute(query: str, vars: Optional[Union[Sequence, Mapping[str, Any]]] = None, polling_time: float = 2, get_schema: bool = True)
```
#### The Description of parameters：
| Parameter Name          | Parameter Type | Mandatory Parameter            | Description           | 
|-------------|----------------|--------------------------------|-------------------------------------------------------------------------------|
| query | str | Yes                            | SQL statement to be executed. |
|vars|Optional[Union[Sequence, Mapping[str, Any]]]|Optional|List of parameters to be bound.|
| polling_time | float | No. The default value is 2.    | Specifies the polling interval for query results. |
| get_schema | bool | No. The default value is True. | Indicates whether to return schema information. |

### Executing Batch SQL Queries: CursorObject.executemany
```python
def executemany(query: str, vars: vars_list: Iterable[Optional[Union[Sequence, Mapping[str, Any]]]] = None, polling_time: float = 2, get_schema: bool = True)
```
#### Parameter description:
| Parameter Name | Parameter Type | Required | Description |
|--------------|-------|------------|----------------|
| query | str | Yes | SQL statement to be executed. |
| vars_list | Iterable[Optional[Union[Sequence, Mapping[str, Any]]]] | No | List of parameters to be bound. |
| polling_time | float | No, default value is 2 | Polling interval for querying results. |
| get_schema | bool | No, default value is True | Whether to return schema information. |

### Return a tuple: CursorObject.fetchone
```python
def fetchone()
```
#### Return: tuple. If the query does not contain a result set, None is returned.

### Return all remaining tuples: CursorObject.fetchall
```python
def fetchall()
```
#### Return: list[tuple]. If the query does not contain a result set, an empty list is returned.

### Switch to the next result set: CursorObject.nextset
```python
def nextset()
```
#### Return: True if the next result set exists; False if the next result set does not exist

### Return an ARROW Batch:CursorObject.fetchbatch
```python
def fetchbatch()
```
#### Back to: one page of ARROW batch data

## The Description of invoking：
- If 2xx is returned, the request is successful. If a value other than 2xx is returned, the requests.exceptions.HTTPError exception is thrown.
- The request timeout interval can be set for all interface methods. If no result is returned within the timeout period, the requests.exceptions.Timeout exception is thrown. For the getStatementResult method, the OBS SDK is used to obtain data. The default timeout interval of the OBS SDK is 60s. Therefore, if timeout is set to None, the OBS SDK will time out after 60s unless timeout is set to a value other than None.

## Example Code
#### Scenario 1:Initialize AuraCLient, create a session, use the session to execute SQL queries, and obtain the result set.
```python
from aura.SQLClient import AuraClient
from aura.SQLRequests import SessionRequest, QueryRequest
import time
# If the AK/SK is a temporary AK/SK, SecurityToken must be provided.
ak = 'xxxxxxxxxx'
sk = 'xxxxxxxxxx'
aura_endpoint = 'xxxxxxxxxx'
endpoint_id = 'xxxxxxxxxx'
workspaceId = 'xxxxxxxxxx'
instance_id = 'xxxxxxxxxx'
catalog = 'xxxxxxxxxx'
# Creating a Aura Client
client = AuraClient(aura_endpoint, ak, sk)
# Create a session request and enter necessary information.
s = SessionRequest()
s.endpoint_id = endpoint_id
s.instance_id = instance_id
s.catalog = catalog
# Create a session and obtain the session ID.
session = client.createSession(workspaceId, s)
session_id = session.session_id
# Create an SQL request.
q = QueryRequest()
q.statement = "select * from table1;"
q.session_id = session_id
# Send a request and return a response.
query_resp = client.executeQuery(workspaceId, q)
# Poll the request result according to the request response.
while True:
    statement_set = client.getSummary(workspaceId, query_resp, get_schema=False)
    print(statement_set.status_code)
    print(statement_set.headers)
    if statement_set.status == "SUCCESSFUL" or statement_set.status == "FAIL":
        break
    # Wait seconds and wait for polling.
    time.sleep(2)
# A statement object indicates the execution result of a single statement.
# If a statement fails to be executed, the statements following the failed statement will not be executed. The returned list contains only the statement object of the failed statement and the previous successful statements.
for statement in statement_set.statements:
    # Obtains the column information of a single statement result set.
    schema = statement.schema
    # Obtains information about columns in a single statement, such as column names.
    for col in schema:
        print(col.name)
    page_count = statement.page_count
    for page_no in range(1, page_count + 1):
        # A result object represents the data set of a single statement page.
        result = client.getStatementResult(workspaceId, statement, page_num=page_no)
        # Print the result tuple data.
        for row in result.result_set.rows:
            print(row)

# Close the session
client.closeSession(workspaceId, session_id)
# Close the AuraClient
client.close()
```

#### Scenario 2: Use the PEP249 standard interface to create a cursor and return a tuple.
```python
from aura.SQLConnector import AuraConnector
from aura.SQLRequests import SessionRequest

# This example demonstrates using AuraConnector in support of the PEP249 standard interface.

ak = 'xxxxxxxxxxxx'
sk = 'xxxxxxxxxxxx'
aura_endpoint = 'xxxxxxxxxx'
endpoint_id = 'xxxxxxxxxxx'
workspace_id = 'xxxxxxxxxxxx'
instance_id = 'xxxxxxxxxxxxx'
catalog = 'xxxxxxxxxx'

# Enter the session creation information.
session = SessionRequest()
session.endpoint_id = endpoint_id
session.instance_id = instance_id
session.catalog = catalog

# Create a connection. A session is created internally.
conn = AuraConnector.connect(aura_endpoint, workspace_id, session, ak, sk)
# Open a cursor
cursor = conn.cursor()
# un SQL statements. Separate multiple statements with semicolons (;).
cursor.execute("select * from table_A")

# Obtains the column information of a query table.
cols = cursor.description
print(cols)

# Obtains a tuple.
one_t = cursor.fetchone()
print(one_t)

# Obtains all remaining tuples.
cursor.fetchall()

# Switch to the next statement result set (if available)
cursor.nextset()

# Close the cursor
cursor.close()
# Close the connection
conn.close()
```

---

# 中文版本

# Aura Python Connector API
*本文档介绍了Aura的Python版本Connector API的代码和使用方法*
## 代码结构：
- aura:库代码文件
- pytest_template:单元测试用例
## 依赖库：
- orjson
- requests
- esdk-obs-python
- six
- zstd
- pandas
- python-dateutil
- pyarrow

*注：安装本Connector API时会自动安装以上依赖库，如安装失败请手动安装*
## Python Connector API接口概览
| 接口名         | 方法                                        | 功能描述                            |
|-------------|-------------------------------------------|---------------------------------|
| 创建session   | AuraClient.createSession             | 创建一个session                     |
| 查询session状态 | AuraClient.getSessionStatus          | 查询一个指定session的状态                |
| 关闭session   | AuraClient.closeSession              | 关闭一个指定的session                  |
| 发送查询请求      | AuraClient.executeQuery              | 下发sql请求                         |
| 查询请求结果      | AuraClient.getSummary                | 查询本次请求的执行结果                     |
| 读取结果集       | AuraClient.getStatementResult        | 查询一个请求的结果集，可以指定查询页数             |
| 取消异步请求      | AuraClient.cancelExecute             | 取消一个执行中的异步请求                    |

同时，Aura Python Connector API支持符合PEP249标准的调用方式，其接口方法如下：
## PEP249标准接口概览
| 接口名     | 方法                         | 功能描述                      |
|---------|----------------------------|---------------------------|
| 创建连接    | AuraConnector.connect | 创建一个连接，返回连接对象Connection   |
| 创建游标    | Connection.cursor          | 创建一个游标，返回游标对象CursorObject |
| 执行SQL请求 | CursorObject.execute       | 使用游标执行SQL查询               |
| 返回一个元组  | CursorObject.fetchone      | 获取查询结果的下一元组               |
| 返回剩余元组  | CursorObject.fetchall      | 获取查询结果的所有剩余元组             |
| 切换下一结果集 | CursorObject.nextset       | 游标切换到下一个结果集，并丢弃当前结果集中剩余元组 |

## 请求体说明：
### `SessionRequest`
#### 同步创建session请求体
#### 参数说明：

| 参数名称                      | 参数类型 | 是否必选 | 描述                                                            | 
|---------------------------|------|------|---------------------------------------------------------------|
| endpoint_id               | str  | 必选   | 执行端点ID。                                                       |
| instance_id | str  | 必选   | LakeFormation实例ID。               |
| catalog_name              | str  | 必选   | LakeFormation Catalog名称。 |
| wait_timeout | str  | 可选   | 创建session排队等待时间，单位秒，取值范围[300, 7200]，有值则为异步创建，不填则为同步创建。              |


### `QueryRequest`
#### SQL请求体
#### 参数说明：

| 参数名称                      | 参数类型            | 是否必选 | 描述              | 
|---------------------------|-----------------|------|-----------------|
| statement | str             | 必选   | 下发SQL内容。        |
| session_id              | str             | 必选   | 会话ID。           |
| limit              | int             | 可选   | SQL limit限制。    |
| bindings              | list[list[str]] | 可选   | 参数绑定。           |

## 响应体说明：
### `SessionResponse`
#### 返回一个创建的session信息
#### 参数说明：

| 参数名称 | 参数类型 | 描述             | 
|------|------|----------------|
|session_id|str| 创建的session的ID。 |
|status|str| 该session的状态。   |


 status取值：

| 状态值 | 描述 |
|-----|----|
| RUNNING | 运行中 |
| CLOSED | 已关闭 |
| WAITING | 等待中|
|CREATING | 创建中|
|FAIL|失败|

### `QueryResponse`
#### 返回SQL请求响应信息
#### 参数说明：

| 参数名称         | 参数类型                     | 描述         | 
|--------------|--------------------------|------------|
| status       | int                      | 总SQL的执行状态。 |
| session_id   | str                      | 会话ID。      |
| statement_id | str                      | 语句ID。      |

### `StatementSet`
#### 本次执行语句总的执行信息
#### 参数说明:
| 参数名称         | 参数类型            | 描述             | 
|--------------|-----------------|----------------|
| status       | str             | 总SQL的执行状态。     |
| statements   | List[Statement] | 本次执行包含的语句执行信息。 |
*注：当SQL请求还未执行完成时，statements为一个空的List。否则会包含每个语句的信息*
 status取值：

| 状态值      | 描述    |
|----------|-------|
| FAIL     | 执行失败  |
| SUCCESSFUL   | 执行成功  |
| RUNNING  | 执行中   |
| EMPTY | 结果集为空 |
| WAITING     | 等待中   |


### `Statement`
#### 单条语句的执行信息
#### 参数说明：
| 参数名称         | 参数类型         | 描述           | 
|--------------|--------------|--------------|
| status       | str          | 该条SQL的执行状态。  |
| statement_id | str          | 语句ID。        |
| session_id   | str          | 执行该语句的会话ID。  |
| num_rows     | int          | 语句总行数。       |
| row_count    | int          | 该页总行数。       |
| page_count   | int          | 总页数。         |
| page_no      | int          | 当前页数，从数字1开始。 |
| err_code     | int          | 错误码。         |
| sql_state    | int          | sql状态码。      |
| message      | str          | 错误信息。        |
| schema       | List[Column] | 该结果集的列信息。    |

status取值：

| 状态值 | 描述                  |
|-----|---------------------|
| PGRES_COMMAND_OK  | 该语句为不返回数据的命令。       |
| PGRES_TUPLES_OK   | 该语句包含数据行。           |
| PGRES_FATAL_ERROR   | 查询失败。               |

### `Result`
#### 语句的结果集信息
#### 参数说明：

| 参数名称         | 参数类型      | 描述           | 
|--------------|-----------|--------------|
| status       | str       | 该条SQL的执行状态。  |
| statement_id | str       | 语句ID。        |
| num_rows     | int       | 语句总行数。       |
| row_count    | int       | 该页总行数。       |
| page_count   | int       | 总页数。         |
| page_no      | int       | 当前页数，从数字1开始。 |
| err_code     | int       | 错误码。         |
| sql_state      | int       | sql状态码。      |
| message      | str       | 错误信息。        |
| result_set   | ResultSet | JSON格式结果集。   |
| arrow_batch | RecordBatch | ARROW格式结果集。|       

ResultSet参数列表：

| 参数名称         | 参数类型         | 描述         | 
|--------------|--------------|------------|
| columns      | list[Column] | 列头数据。      |
| rows         | list[list[str]]    | 列数据。       |

Column参数列表：

| 参数名称     | 参数类型 | 描述     | 
|----------|------|--------|
| name     | str  | 列头名称。  |
| table_id | int  | 表的ID。  |
| colunm_id | int  | 列的ID。  |
| format   | int  | 格式。    |
| type     | int  | 类型。    |
| size     | int  | 大小。    |
| typemod  | int  | typemod。 |
 status取值：

| 状态值 | 描述                  |
|-----|---------------------|
| -1  | 执行失败（FAILED)。       |
| 0   | 执行成功（SUCCESSFUL)。   |
| 1   | 正在执行（RUNNING)。      |
| 2   | 指令执行完成，无返回值（EMPTY)。 |
| 3   | 正在排队等待执行（WAITING)。  |

## 方法说明：
### 初始化客户端
```python
def AuraClient(endpoint, accessKey, secretKey, token, securityToken=None, proxies=None, verify=False)
```
#### 参数说明:

| 参数名称          | 参数类型 | 是否必选        | 描述                                                                             | 
|---------------|------|-------------|--------------------------------------------------------------------------------|
| endpoint      | str  | 必选          | 指定服务的区域，区域查询[地区和终端节点](https://console.huaweicloud.com/apiexplorer/#/endpoint)。 |
| accessKey     | str  | 必选          | 接入键标识。                                                                         | 
| secretKey     | str  | 必选          | 安全接入键。                                                                         | 
| token         | str  | 可选          | IAM用户Token。                                                                    | 
| securityToken | str  | 可选          | 使用临时AK/SK时需要提供。                                                                |
| proxies       | dict | 可选          | 是否使用代理，如果不填则默认使用系统代理。                                                          |
| verify        | bool | 可选，默认为False | 是否验证服务器的 SSL 证书。                                                               |
*注：<br>1）用户提供永久AK和SK时，可不填入securityToken，当使用临时AK和SK时，必须填入securityToken,请参阅[获取临时AKSK方法](https://support.huaweicloud.com/usermanual-ca/ca_01_0003.html)。<br>2）IAM Token为可选项，当用户提供了IAM Token时，优先使用Token访问Aura API服务，否则使用访问密钥访问Aura API服务。获取Token请参考：[获取IAM用户Token](https://support.huaweicloud.com/api-iam/iam_30_0001.html)。*
#### 返回：AuraClient客户端实例

### 创建session
```python
def createSession(workspaceId, request, timeout=None)
```
#### 参数说明：

| 参数名称                      | 参数类型           | 是否必选 | 描述                   | 
|---------------------------|----------------|------|----------------------|
| workspaceId | str            | 必选   | 用户创建的Aura的工作空间的ID。 |
| request                      | sessionRequest | 必选   | session请求信息。         |
| timeout | float          | 可选   | 请求超时时间。              |
#### 返回：session实例响应类`SessionResponse`

### 查询session状态
```python
def getSessionStatus(workspaceId, sessionId, timeout=None)
```
#### 参数说明：

| 参数名称        | 参数类型  | 是否必选 | 描述                   | 
|-------------|-------|------|----------------------|
| workspaceId | str   | 必选   | 用户创建的Aura的工作空间的ID。 |
| sessionId   | str   | 必选   | 指定要查询session的id。     |
| timeout     | float | 可选   | 请求超时时间。              |
#### 返回：字符串
 session状态取值：

| 状态值 | 描述 |
|-----|----|
| RUNNING | 运行中 |
| CLOSED | 已关闭 |
| WAITING | 等待中|
|CREATING | 创建中|
|FAIL|失败|

### 关闭session
```python
def closeSession(workspaceId, sessionId, timeout=None)
```
#### 参数说明：

| 参数名称        | 参数类型  | 是否必选 | 描述                   | 
|-------------|-------|------|----------------------|
| workspaceId | str   | 必选   | 用户创建的Aura的工作空间的ID。 |
| sessionId   | str   | 必选   | 指定要关闭session的id。     |
| timeout     | float | 可选   | 请求超时时间。              |
#### 返回：空响应体

### 发送SQL请求
```python
def executeQuery(workspaceId, request, timeout=None)
```
#### 参数说明：

| 参数名称                      | 参数类型         | 是否必选 | 描述                   | 
|---------------------------|--------------|------|----------------------|
| workspaceId | str          | 必选   | 用户创建的Aura的工作空间的ID。 |
| request                      | QueryRequest | 必选   | SQL请求类。              |
| timeout | float        | 可选   | 请求超时时间。              |
#### 返回：SQL请求响应类`QueryResponse`


### 查询请求结果
```python
def getSummary(workspaceId, query_resp, get_schema=True, timeout=None)
```
#### 参数说明：
| 参数名称                      | 参数类型          | 是否必选 | 描述                        | 
|---------------------------|---------------|------|---------------------------|
| workspaceId | str           | 必选   | 用户创建的Aura的工作空间的ID。      |
| query_resp                     | QueryResponse | 必选   | 查询响应类。                    |
| get_schema                    | bool          | 可选   | 是否返回查询表的schema信息，默认为True。 |
| timeout | float         | 可选   | 请求超时时间。                   |
#### 返回：`StatementSet`

### 获取查询结果集
```python
def getStatementResult(statement, page_num=1, from_obs: bool = True, convert_type: bool = False, workspaceId=None, timeout=None)
```
#### 参数说明：

| 参数名称        | 参数类型      | 是否必选        | 描述                                          | 
|-------------|-----------|-------------|---------------------------------------------|
| statement   | Statement | 必选          | 查询语句的信息。                                    |
| page_num    | int       | 可选          | 默认值为1，查询结果集的指定页数，当指定页数超过该查询结果集总页数时会返回空结果集。  |
| from_obs | bool      | 可选，默认为True  | 指定是否直接从OBS获取结果集。                            |
|convert_type|bool| 可选，默认为False | 指定是否根据数据类型OID转换为对应Python数据类型。               |
| workspaceId | str       | 可选          | 用户创建的Aura的工作空间的ID，当from_obs为False时必须传入该参数 |
| timeout     | float     | 可选          | 请求超时时间。                                     |
#### 返回：结果集类`Result`
*注：因为OBS SDK默认HTTPS超时时间是60s, 且不支持将timeout设置为None，故当用户将timeout设置为None时，将OBS超时时间设置为默认值。*

### 取消查询请求
```python
def cancelExecute(workspaceId, response, timeout=None)
```
#### 参数说明：
| 参数名称        | 参数类型  | 是否必选 | 描述                   | 
|-------------|-------|------|----------------------|
| workspaceId | str   | 必选   | 用户创建的Aura的工作空间的ID。 |
| response   | QueryResponse   | 必选   | 想要取消查询的请求体。          |
| timeout     | float | 可选   | 请求超时时间 。             |
#### 返回： 空响应体

## PEP249标准方法说明：
### 创建连接：AuraConnector.connect
```python
def connect(endpoint: str,
            workspaceId: str,
            request: SessionRequest,
            accessKey: str,
            secretKey: str,
            token: str = None,
            securityToken: str = None,
            timeout: float = None,
            proxies: dict = None,
            verify: bool = False,
            concurrent_max_worker: int = 1,
            from_obs: bool = True
)
```
#### 参数说明：
| 参数名称        | 参数类型           | 是否必选        | 描述                                                                            | 
|-------------|----------------|-------------|-------------------------------------------------------------------------------|
| endpoint      | str            | 必选          | 指定服务的区域，区域查询[地区和终端节点](https://console.huaweicloud.com/apiexplorer/#/endpoint)。 |
| workspaceId | str            | 必选          | 用户创建的Aura的工作空间的ID。                                                          |
| request                      | sessionRequest | 必选          | session请求信息。                                                                  |
| accessKey     | str            | 必选          | 接入键标识。                                                                        | 
| secretKey     | str            | 必选          | 安全接入键。                                                                        | 
| token         | str            | 可选          | IAM用户Token。                                                                   | 
| securityToken | str            | 可选          | 使用临时AK/SK时需要提供。                                                               |
| timeout     | float          | 可选          | 请求超时时间。                                                                       |
| proxies       | dict           | 可选          | 是否使用代理，如果不填则默认使用系统代理。                                                         |
| verify        | bool           | 可选，默认为False | 是否验证服务器的 SSL 证书。                                                              |
| concurrent_max_worker                      | int            | 可选，默认为1     | 控制获取结果集页的并发数。        |
| from_obs | bool      | 可选，默认为True | 指定是否直接从OBS获取结果集。                           |
#### 返回： 连接对象Connection

### 创建游标：Connection.cursor
```python
def cursor()
```
#### 返回： 游标对象CursorObject


### 执行SQL查询：CursorObject.execute
```python
def execute(query: str, vars: Optional[Union[Sequence, Mapping[str, Any]]] = None, polling_time: float = 2, get_schema: bool = True)
```
#### 参数说明：
| 参数名称  | 参数类型  | 是否必选       | 描述             | 
|-------|-------|------------|----------------|
| query | str   | 必选         | 需要执行的SQL语句。    |
|vars|Optional[Union[Sequence, Mapping[str, Any]]]|可选|要绑定的参数列表。|
| polling_time | float | 可选，默认值为2   | 控制查询结果的轮询时间间隔。 |
| get_schema | bool  | 可选，默认为True | 是否返回schema信息。  |

### 执行批量SQL查询：CursorObject.executemany
```python
def executemany(query: str, vars: vars_list: Iterable[Optional[Union[Sequence, Mapping[str, Any]]]] = None, polling_time: float = 2, get_schema: bool = True)
```
#### 参数说明：
| 参数名称         | 参数类型  | 是否必选       | 描述             | 
|--------------|-------|------------|----------------|
| query        | str   | 必选         | 需要执行的SQL语句。    |
| vars_list    |Iterable[Optional[Union[Sequence, Mapping[str, Any]]]]|可选|要绑定的参数列表。|
| polling_time | float | 可选，默认值为2   | 控制查询结果的轮询时间间隔。 |
| get_schema   | bool  | 可选，默认为True | 是否返回schema信息。  |


### 返回一个元组：CursorObject.fetchone
```python
def fetchone()
```
#### 返回：tuple，当查询不包含结果集时，返回None

### 返回剩余所有元组：CursorObject.fetchall
```python
def fetchall()
```
#### 返回：list[tuple],当查询不包含结果集时，返回空list

### 切换下一结果集：CursorObject.nextset
```python
def nextset()
```
#### 返回：当存在下一结果集时返回True，否则返回False

### 返回一个ARROW BATCH:CursorObject.fetchbatch
```python
def fetchbatch()
```
#### 返回：一页ARROW BATCH数据

## 调用说明：
- 请求返回2xx表示返回成功，返回2xx以外的值会抛出requests.exceptions.HTTPError异常。
- 所有接口方法可以设置请求超时时间timeout，当请求在timeout设定值之内没有返回结果，会抛出requests.exceptions.Timeout异常。对于getStatementResult方法，使用OBS SDK获取数据，OBS SDK内置默认超时时间是60s，所以如果timeout设置为None，OBS SDK也会在60s后超时，除非指定timeout值为非None。

## 示例代码：
#### 场景一：初始化AuraCLient，创建session，并使用该session执行SQL查询，然后获取结果集
```python
from aura.SQLClient import AuraClient
from aura.SQLRequests import SessionRequest, QueryRequest
import time
# 如果是临时AK\SK，还需要提供SecurityToken
ak = 'xxxxxxxxxx'
sk = 'xxxxxxxxxx'
aura_endpoint = 'xxxxxxxxxx'
endpoint_id = 'xxxxxxxxxx'
workspaceId = 'xxxxxxxxxx'
instance_id = 'xxxxxxxxxx'
catalog = 'xxxxxxxxxx'
# 创建一个Aura客户端
client = AuraClient(aura_endpoint, ak, sk)
# 创建一个session请求，填入必要信息
s = SessionRequest()
s.endpoint_id = endpoint_id
s.instance_id = instance_id
s.catalog = catalog
# 创建一个session,获取session_id
session = client.createSession(workspaceId, s)
session_id = session.session_id
# 创建一个SQL请求
q = QueryRequest()
q.statement = "select * from table1;"
q.session_id = session_id
# 下发请求，返回一个请求响应
query_resp = client.executeQuery(workspaceId, q)
# 根据该请求响应，轮询请求结果
while True:
    statement_set = client.getSummary(workspaceId, query_resp, get_schema=False)
    print(statement_set.status_code)
    print(statement_set.headers)
    if statement_set.status == "SUCCESSFUL" or statement_set.status == "FAIL":
        break
    #等待2s后轮询
    time.sleep(2)
# 一个Statement结构体代表一个单语句的执行结果
# 如果用户执行多个语句中存在某个语句执行失败，则失败语句之后的语句不会被执行，返回的list中只会包含该失败语句和之前成功语句的Statement结构体
for statement in statement_set.statements:
    # 获取单个语句结果集的列信息
    schema = statement.schema
    # 获取单个语句中列的信息，比如列名
    for col in schema:
        print(col.name)
    page_count = statement.page_count
    for page_no in range(1, page_count + 1):
        # 一个Result结构体代表单个语句一页的数据集
        result = client.getStatementResult(workspaceId, statement, page_num=page_no)
        # 打印出结果行数据
        for row in result.result_set.rows:
            print(row)

# 关闭一个session
client.closeSession(workspaceId, session_id)
# 关闭AuraClient
client.close()
```

#### 场景二：使用PEP249标准接口，创建游标并返回元组
```python
from aura.SQLConnector import AuraConnector
from aura.SQLRequests import SessionRequest

# 本示例程序演示支持PEP249标准接口使用AuraConnector

ak = 'xxxxxxxxxxxx'
sk = 'xxxxxxxxxxxx'
aura_endpoint = 'xxxxxxxxxx'
endpoint_id = 'xxxxxxxxxxx'
workspace_id = 'xxxxxxxxxxxx'
instance_id = 'xxxxxxxxxxxxx'
catalog = 'xxxxxxxxxx'

# 填入创建session信息
session = SessionRequest()
session.endpoint_id = endpoint_id
session.instance_id = instance_id
session.catalog = catalog

# 创建连接，内部会创建一个session
conn = AuraConnector.connect(aura_endpoint, workspace_id, session, ak, sk)
# 打开一个游标
cursor = conn.cursor()
# 执行SQL语句，多个语句请使用分号隔开
cursor.execute("select * from table_A")

# 获取查询表列信息
cols = cursor.description
print(cols)

# 获取一条元组
one_t = cursor.fetchone()
print(one_t)

# 获取剩余所有元组
cursor.fetchall()

# 获取下一个语句结果集(如果存在)
cursor.nextset()

# 关闭游标
cursor.close()
# 关闭连接
conn.close()
```
