cdata-connect-ai 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 CData Software, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,132 @@
1
+ ## Overview
2
+
3
+ The Python Connector for CData Connect allows developers to write Python scripts with connectivity to CData Connect. The connector wraps the complexity of accessing CData Connect data in an interface commonly used by python connectors to common database systems.
4
+
5
+ ## Establishing a Connection
6
+ The objects available within our connector are accessible from the "cdata_connect_ai" module. In order to use the module's objects directly, the module must first be imported.Then, you can establish a connection in one of two ways:
7
+
8
+ ```
9
+ from cdata_connect_ai import Connection
10
+ conn = Connection(base_url= "https://cloud.cdata.com/api/",
11
+ username= "example@example.com",
12
+ password= "<your_personal_access_token_here>")
13
+ ```
14
+ ```
15
+ import cdata_connect_ai as mod
16
+ conn = mod.connect(base_url= "https://cloud.cdata.com/api/",
17
+ username= "example@example.com",
18
+ password= "<your_personal_access_token_here>")
19
+ ```
20
+ ## PyHOCON Config file
21
+ This library supports PyHOCON formatted config files to pass as a parameter for Connection the the CData cloud.
22
+ An example `config.conf` can look like:
23
+
24
+ ```
25
+ cdata_api_db {
26
+ base_url = "https://cloud.cdata.com/api/"
27
+ username = "example@example.com"
28
+ password = "<your_personal_access_token_here>"
29
+ }
30
+ ```
31
+
32
+ You can then pass this config file as a parameter to the Connection class like so:
33
+
34
+ ```
35
+ from cdata_connect_ai import Connection
36
+ conn = Connection(config_path="config.conf")
37
+ ```
38
+ or
39
+ ```
40
+ import cdata_connect_ai as mod
41
+ conn = mod.connect(config_path="config.conf")
42
+ ```
43
+
44
+ ## Cursor
45
+ After establishing a connection, you can create a cursor like so:
46
+ ```
47
+ cursor = conn.cursor()
48
+ ```
49
+
50
+ You can then make queries like so:
51
+ ```
52
+ query = """SELECT * FROM [Test1].[OData].[Airlines]"""
53
+ cursor.execute(query)
54
+ result = cursor.fetchall()
55
+ for row in result:
56
+ print(row)
57
+ ```
58
+
59
+ ### Parameterised Queries
60
+ This library supports the Pyformat protocol for making parameterised queries. You can make these queries with a `params` dictionary like so:
61
+ ```
62
+ params = {
63
+ "id": 123,
64
+ "name": "John Doe"
65
+ }
66
+
67
+ query = "SELECT * FROM users WHERE id = %(id)s AND name = %(name)s"
68
+ cursor.execute(query, params)
69
+ ```
70
+ ## Batch Operation
71
+ The batch operation allows you to execute batch INSERTs, UPDATEs, and DELETEs against your data sources using a single request.
72
+
73
+ To execute a batch operation,
74
+
75
+ ```
76
+ params = [
77
+ {
78
+ "@p1": {"dataType": 5, "value": "New York"},
79
+ "@p2": {"dataType": 8, "value": 107},
80
+ },
81
+ {
82
+
83
+ "@p1": {"dataType": 5, "value": 'London'},
84
+ "@p2": {"dataType": 8, "value": 108},
85
+ }
86
+ ]
87
+ query = """INSERT INTO PostgreSQL1.public.city (city, country_id)
88
+ VALUES (@p1, @p2)"""
89
+ cursor.executemany(query=query, schema="PostgreSQL1.public", params=params)
90
+ ```
91
+ ## Execute Procedures
92
+ The execute operation allows you to execute stored procedures for any of the data sources configured in your CData Connect account.
93
+
94
+ ```
95
+ params = {
96
+ "@p_film_title": {
97
+ "dataType": 5,
98
+ "value": "Academy Dinosaur"
99
+ },
100
+ "@p_new_rate": {
101
+ "dataType": 8,
102
+ "value": 2
103
+ }
104
+ }
105
+ query = """select update_film_rental_rate(@p1, @p2)"""
106
+ cursor.callproc(params=params, procedure="PostgreSQL1.public.update_film_rental_rate")
107
+ ```
108
+
109
+
110
+ ## Multithreading
111
+ This library supports multithreading. You can make use of that like so:
112
+ ```
113
+ import threading
114
+
115
+ def execute_query(thread_id):
116
+ conn = Connection(config_path="main\config.conf")
117
+ cursor = conn.cursor()
118
+ query = "SELECT * FROM [Test1].[OData].[Airlines]"
119
+ cursor.execute(query)
120
+ resultone = cursor.fetchall()
121
+ print(resultone)
122
+
123
+
124
+ threads = []
125
+ for i in range(5):
126
+ thread = threading.Thread(target=execute_query, args=(i,))
127
+ threads.append(thread)
128
+ thread.start()
129
+
130
+ for thread in threads:
131
+ thread.join()
132
+ ```
@@ -0,0 +1,82 @@
1
+ from typing import Optional
2
+
3
+ from .connection import Connection, DEFAULT_BASE_URL
4
+ from .exceptions import (
5
+ ConfigurationError,
6
+ DatabaseError,
7
+ DataError,
8
+ Error,
9
+ IntegrityError,
10
+ InterfaceError,
11
+ InternalError,
12
+ NotSupportedError,
13
+ OperationalError,
14
+ ProgrammingError,
15
+ Warning,
16
+ )
17
+ from .util.types import (
18
+ DBAPI_TYPE_STRING,
19
+ DBAPI_TYPE_BINARY,
20
+ DBAPI_TYPE_NUMBER,
21
+ DBAPI_TYPE_TIMESTAMP,
22
+ Date,
23
+ Time,
24
+ Timestamp,
25
+ Binary,
26
+ DateFromTicks,
27
+ TimeFromTicks,
28
+ TimestampFromTicks,
29
+ )
30
+ from .version import __version__
31
+
32
+ # PEP 249 mandatory module-level type objects
33
+ STRING = DBAPI_TYPE_STRING # 0
34
+ BINARY = DBAPI_TYPE_BINARY # 1
35
+ NUMBER = DBAPI_TYPE_NUMBER # 2
36
+ DATETIME = DBAPI_TYPE_TIMESTAMP # 3
37
+ ROWID = DBAPI_TYPE_STRING # No dedicated ROWID type; STRING is the standard fallback
38
+
39
+ # DB API 2.0 module attributes
40
+ apilevel = "2.0"
41
+ threadsafety = 1
42
+ paramstyle = "pyformat"
43
+
44
+
45
+ def connect(
46
+ config_path: Optional[str] = None,
47
+ base_url: Optional[str] = None,
48
+ username: Optional[str] = None,
49
+ password: Optional[str] = None,
50
+ workspace: Optional[str] = None,
51
+ timeout: int = 90,
52
+ max_retries: int = 3,
53
+ retry_delay: float = 1.0,
54
+ ) -> Connection:
55
+ """
56
+ Create a connection to the CData Connect AI API.
57
+
58
+ :param base_url: The base URL of the CData Connect AI API.
59
+ :param username: The username for authentication.
60
+ :param password: The password for authentication.
61
+ :param config_path: Optional path to a pyhocon config file.
62
+ :param workspace: Optional workspace name to append as a query parameter.
63
+ :param timeout: HTTP request timeout in seconds (per socket read). Default 90.
64
+ :param max_retries: Retry count for transient 5xx errors. Default 3.
65
+ :param retry_delay: Base seconds between retries (exponential backoff). Default 1.0.
66
+ :return: A Connection object.
67
+ """
68
+ if not config_path and not (username and password):
69
+ raise InterfaceError(
70
+ "Either config_path or username and password must be provided."
71
+ )
72
+
73
+ return Connection(
74
+ config_path=config_path,
75
+ base_url=base_url,
76
+ username=username,
77
+ password=password,
78
+ workspace=workspace,
79
+ timeout=timeout,
80
+ max_retries=max_retries,
81
+ retry_delay=retry_delay,
82
+ )
@@ -0,0 +1,34 @@
1
+ # file generated by setuptools-scm
2
+ # don't change, don't track in version control
3
+
4
+ __all__ = [
5
+ "__version__",
6
+ "__version_tuple__",
7
+ "version",
8
+ "version_tuple",
9
+ "__commit_id__",
10
+ "commit_id",
11
+ ]
12
+
13
+ TYPE_CHECKING = False
14
+ if TYPE_CHECKING:
15
+ from typing import Tuple
16
+ from typing import Union
17
+
18
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
19
+ COMMIT_ID = Union[str, None]
20
+ else:
21
+ VERSION_TUPLE = object
22
+ COMMIT_ID = object
23
+
24
+ version: str
25
+ __version__: str
26
+ __version_tuple__: VERSION_TUPLE
27
+ version_tuple: VERSION_TUPLE
28
+ commit_id: COMMIT_ID
29
+ __commit_id__: COMMIT_ID
30
+
31
+ __version__ = version = '1.0.0'
32
+ __version_tuple__ = version_tuple = (1, 0, 0)
33
+
34
+ __commit_id__ = commit_id = None
@@ -0,0 +1,122 @@
1
+ from pyhocon import ConfigFactory
2
+ from pyhocon.exceptions import ConfigException
3
+ from warnings import warn
4
+
5
+ from .cursor import Cursor
6
+ from .log import logger
7
+ from .exceptions import (
8
+ ConfigurationError, InterfaceError, Warning, Error,
9
+ DatabaseError, OperationalError, IntegrityError,
10
+ InternalError, ProgrammingError, NotSupportedError,
11
+ )
12
+
13
+
14
+ DEFAULT_BASE_URL = "https://cloud.cdata.com/api"
15
+
16
+
17
+ class Connection:
18
+ """
19
+ Create a connection to the CData Connect AI API.
20
+
21
+ :param base_url: The base URL of the CData Connect AI API.
22
+ Defaults to ``https://cloud.cdata.com/api``.
23
+ :param username: The username for authentication.
24
+ :param password: The password for authentication.
25
+ :param config_path: Optional path to a config file in pyhocon format.
26
+ :param workspace: Optional arg to access a specific CData workspace.
27
+ :param timeout: HTTP request timeout in seconds (per socket read). Default 90.
28
+ :param max_retries: Number of retries on transient 5xx / connection errors. Default 3.
29
+ :param retry_delay: Base delay in seconds between retries (exponential backoff). Default 1.0.
30
+ """
31
+ # DBAPI Extension: supply exceptions as attributes on the connection
32
+ Warning = property(lambda self: self._getError(Warning))
33
+ Error = property(lambda self: self._getError(Error))
34
+ InterfaceError = property(lambda self: self._getError(InterfaceError))
35
+ DatabaseError = property(lambda self: self._getError(DatabaseError))
36
+ OperationalError = property(lambda self: self._getError(OperationalError))
37
+ IntegrityError = property(lambda self: self._getError(IntegrityError))
38
+ InternalError = property(lambda self: self._getError(InternalError))
39
+ ProgrammingError = property(lambda self: self._getError(ProgrammingError))
40
+ NotSupportedError = property(lambda self: self._getError(NotSupportedError))
41
+
42
+ def _getError(self: "Connection", error):
43
+ warn("DB-API extension connection.%s used" % error.__name__, stacklevel=3)
44
+ return error
45
+
46
+ def __init__(self, base_url: str = None, username: str = None,
47
+ password: str = None, config_path: str = None,
48
+ workspace: str = None, timeout: int = 90,
49
+ max_retries: int = 3, retry_delay: float = 1.0):
50
+
51
+ self.is_open = True
52
+ self.timeout = timeout
53
+ self.max_retries = max_retries
54
+ self.retry_delay = retry_delay
55
+ self.workspace = workspace
56
+
57
+ if config_path:
58
+ logger.debug("Connection - Initialising Connection with config")
59
+ try:
60
+ config = ConfigFactory.parse_file(config_path)
61
+ except (ConfigException, FileNotFoundError) as e:
62
+ raise ConfigurationError(
63
+ f"Configuration file could not be loaded: {str(e)}"
64
+ ) from e
65
+
66
+ try:
67
+ config_base_url = config.get_string('cdata_api_db.base_url')
68
+ self.base_url = config_base_url.rstrip('/')
69
+ self.auth = (config.get_string('cdata_api_db.username'),
70
+ config.get_string('cdata_api_db.password'))
71
+ except (ConfigException, KeyError) as e:
72
+ raise ConfigurationError(
73
+ f"Missing required configuration in cdata_api_db block: {str(e)}"
74
+ ) from e
75
+
76
+ else:
77
+ logger.debug("Connection - Initialising Connection with "
78
+ "username and password")
79
+
80
+ if username is None or password is None:
81
+ raise ConfigurationError(
82
+ "Missing required parameters: username and password "
83
+ "must be provided."
84
+ )
85
+
86
+ self.base_url = (base_url or DEFAULT_BASE_URL).rstrip('/')
87
+ self.auth = (username, password)
88
+
89
+ # ------------------------------------------------------------------
90
+ # Context manager (PEP 249 optional extension)
91
+ # ------------------------------------------------------------------
92
+
93
+ def __enter__(self):
94
+ return self
95
+
96
+ def __exit__(self, exc_type, exc_val, exc_tb):
97
+ self.close()
98
+ return False
99
+
100
+ # ------------------------------------------------------------------
101
+ # DB API 2.0 methods
102
+ # ------------------------------------------------------------------
103
+
104
+ def commit(self):
105
+ """Commit any pending transaction. No-op — underlying API has no transactions."""
106
+ if self.is_open is False:
107
+ raise InterfaceError("Cannot commit because the connection is already closed.")
108
+
109
+ def rollback(self):
110
+ """Rollback any pending transaction. No-op — underlying API has no transactions."""
111
+ if self.is_open is False:
112
+ raise InterfaceError("Cannot rollback because the connection is already closed.")
113
+
114
+ def close(self):
115
+ if self.is_open is False:
116
+ raise InterfaceError("The connection is already closed")
117
+ self.is_open = False
118
+
119
+ def cursor(self):
120
+ if self.is_open is False:
121
+ raise InterfaceError("Cannot create cursor: connection is closed")
122
+ return Cursor(self)