eq-sql-connector 0.1.0__tar.gz

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) 2025 Equinor
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,37 @@
1
+ Metadata-Version: 2.3
2
+ Name: eq-sql-connector
3
+ Version: 0.1.0
4
+ Summary: SQL Database connector to connect to public client app registrations using delegated permissions (MSAL).
5
+ License: MIT
6
+ Author: Åsmund Våge Fannemel
7
+ Author-email: asmf@equinor.com
8
+ Requires-Python: >=3.10,<4.0
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Requires-Dist: msal-bearer (>=1.4.3,<2.0.0)
16
+ Requires-Dist: pandas (>=2.3.2,<3.0.0)
17
+ Requires-Dist: pyodbc (>=5.2.0,<6.0.0)
18
+ Requires-Dist: sqlalchemy (>=2.0.43,<3.0.0)
19
+ Description-Content-Type: text/markdown
20
+
21
+ # eq-sql-connector
22
+ A small python package to handle authentication and act as a generic database connector.
23
+
24
+ It supports multiple authentication flows using [msal-bearer](https://github.com/equinor/msal-bearer) and contains a few basic database functions including a simple function including parameterized querying.
25
+
26
+ # Install
27
+ Install from pypi ```pip install eq-sql-connector``` or clone and use ```poetry install``` as a developer.
28
+
29
+ # Usage
30
+ Dummy example to come
31
+
32
+ ```
33
+
34
+ ````
35
+
36
+
37
+
@@ -0,0 +1,16 @@
1
+ # eq-sql-connector
2
+ A small python package to handle authentication and act as a generic database connector.
3
+
4
+ It supports multiple authentication flows using [msal-bearer](https://github.com/equinor/msal-bearer) and contains a few basic database functions including a simple function including parameterized querying.
5
+
6
+ # Install
7
+ Install from pypi ```pip install eq-sql-connector``` or clone and use ```poetry install``` as a developer.
8
+
9
+ # Usage
10
+ Dummy example to come
11
+
12
+ ```
13
+
14
+ ````
15
+
16
+
@@ -0,0 +1,9 @@
1
+ import logging
2
+
3
+ from eq_sql_connector.connector import DBConnector
4
+
5
+ __all__ = [
6
+ "DBConnector",
7
+ ]
8
+
9
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
@@ -0,0 +1,260 @@
1
+ import json
2
+ import logging
3
+ import struct
4
+ from abc import ABC
5
+ from types import SimpleNamespace
6
+ from typing import Optional
7
+
8
+ import pandas as pd
9
+ import pyodbc
10
+ from msal_bearer import Authenticator, get_user_name
11
+ from sqlalchemy import URL, Engine, QueuePool, create_engine, text, bindparam
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ def get_object_from_json(text: str):
17
+ if isinstance(text, list):
18
+ obj = [json.loads(x, object_hook=lambda d: SimpleNamespace(**d)) for x in text]
19
+ else:
20
+ obj = json.loads(text, object_hook=lambda d: SimpleNamespace(**d))
21
+ return obj
22
+
23
+
24
+ def get_sql_driver() -> str:
25
+ """Get name of ODBC SQL driver
26
+
27
+ Raises:
28
+ ValueError: Raised if required ODBC driver is not installed.
29
+
30
+ Returns:
31
+ str: ODBC driver name
32
+ """
33
+
34
+ drivers = pyodbc.drivers()
35
+
36
+ for driver in drivers:
37
+ if "18" in driver and "SQL Server" in driver:
38
+ return driver
39
+
40
+ for driver in drivers:
41
+ if "17" in driver and "SQL Server" in driver:
42
+ return driver
43
+
44
+ raise ValueError("ODBC driver 17 or 18 for SQL server is required.")
45
+
46
+
47
+ def get_connection_string(
48
+ server: str, database: str, driver: str = get_sql_driver()
49
+ ) -> str:
50
+ """Build database connection string
51
+
52
+ Args:
53
+ server (str): Server url
54
+ database (str): Database name
55
+ driver (str): ODBC driver name. Defaults to get_sql_driver().
56
+
57
+ Returns:
58
+ str: Database connection string
59
+ """
60
+ return f"DRIVER={driver};SERVER={server};DATABASE={database};"
61
+
62
+
63
+ _eq_tenant_id = "3aa4a235-b6e2-48d5-9195-7fcf05b459b0"
64
+ _clientID = "9ed0d36d-1034-475a-bdce-fa7b774473fb" # pdm-tools works for all :)
65
+ _scopes = ["https://database.windows.net/.default"]
66
+
67
+
68
+ class Connector(ABC):
69
+ def __init__(
70
+ self,
71
+ authenticator: Optional[Authenticator] = None,
72
+ url_prod: Optional[str] = None,
73
+ url_dev: Optional[str] = None,
74
+ ) -> None:
75
+ self._use_dev = False
76
+ if url_dev is not None:
77
+ self._url_dev = url_dev
78
+ self.set_use_dev(True)
79
+ else:
80
+ self._url_dev = ""
81
+
82
+ if url_prod is not None:
83
+ self._url_prod = url_prod
84
+ self.set_use_dev(False)
85
+ else:
86
+ self._url_prod = ""
87
+
88
+ if authenticator is None:
89
+ authenticator = Authenticator(
90
+ tenant_id=_eq_tenant_id,
91
+ client_id=_clientID,
92
+ scopes=_scopes,
93
+ user_name=f"{get_user_name()}@equinor.com",
94
+ )
95
+ self.set_Authenticator(authenticator=authenticator)
96
+
97
+ def set_url_prod(self, url: str) -> None:
98
+ """Setter for property _url_prod.
99
+
100
+ Args:
101
+ url (str): URL to set.
102
+ """
103
+ self._url_prod = url
104
+
105
+ def set_url_dev(self, url: str) -> None:
106
+ """Setter for property _url_dev.
107
+
108
+ Args:
109
+ url (str): URL to set.
110
+ """
111
+ self._url_dev = url
112
+
113
+ def set_use_dev(self, use_dev: bool):
114
+ """Setter for global property _use_dev.
115
+ If _use_dev is True, the API URL will be set to the development URL,
116
+ otherwise it will be set to the production URL.
117
+
118
+ Args:
119
+ use_dev (bool): Value to set _use_dev to.
120
+
121
+ Raises:
122
+ TypeError: In case input use_dev is not a boolean.
123
+ """
124
+ if not isinstance(use_dev, bool):
125
+ raise TypeError("Input use_dev shall be boolean.")
126
+
127
+ self._use_dev = use_dev
128
+
129
+ def get_url(self) -> str:
130
+ """Getter for URL. Will return the dev URL if _use_dev is True, otherwise will return the production URL.
131
+ Returns:
132
+ str: API URL
133
+ """
134
+ if self._use_dev:
135
+ return self._url_dev
136
+ else:
137
+ return self._url_prod
138
+
139
+ def set_Authenticator(self, authenticator: Authenticator) -> None:
140
+ """Setter for property authenticator.
141
+
142
+ Args:
143
+ authenticator (Authenticator): Authenticator to set.
144
+ """
145
+ if not isinstance(authenticator, Authenticator):
146
+ raise TypeError("Input authenticator shall be of type Authenticator.")
147
+
148
+ self.authenticator = authenticator
149
+
150
+
151
+ class DBConnector(Connector):
152
+ def __init__(
153
+ self,
154
+ database,
155
+ authenticator: Optional[Authenticator] = None,
156
+ url_prod: Optional[str] = None,
157
+ url_dev: Optional[str] = None,
158
+ ) -> None:
159
+ super().__init__(
160
+ authenticator=authenticator, url_prod=url_prod, url_dev=url_dev
161
+ )
162
+
163
+ self.Engine = None
164
+ self.conn_string = get_connection_string(
165
+ server=self.get_url(), database=database
166
+ )
167
+
168
+ def query(
169
+ self,
170
+ sql: str,
171
+ params: Optional[dict] = None,
172
+ ) -> pd.DataFrame:
173
+ """Query SQL database using pd.read_sql
174
+
175
+ Args:
176
+ sql (str): SQL query for database
177
+ connection (Optional[Connection], optional): Database Connection object. Defaults to None, which resolves to get_connection().
178
+ params (Optional[dict], optional): SQL parameters. Defaults to None.
179
+
180
+ Returns:
181
+ pd.DataFrame: Result from pd.read_sql
182
+ """
183
+
184
+ # Format SQL query and parameters
185
+ if isinstance(params, dict) and "param" in params:
186
+ pass
187
+ else:
188
+ params = {"param": params}
189
+
190
+ sql_clause = text(sql)
191
+ sql_clause = sql_clause.bindparams(bindparam("param", expanding=True))
192
+
193
+ return pd.read_sql(sql_clause, self.get_engine(), params=params)
194
+
195
+ def reset_engine(self) -> None:
196
+ """Reset cached Engine"""
197
+
198
+ if self.Engine is not None:
199
+ self.Engine.dispose()
200
+ self.Engine = None
201
+
202
+ def get_engine(self, conn_string="", token="", reset=False) -> Engine:
203
+ """Getter of cached Engine. Will create one if not existing.
204
+
205
+ Args:
206
+ conn_string (str, optional): Connection string for odbc connection. Defaults to "" to support just getting cached engine.
207
+ token (str, optional): Token string. Defaults to "" to support just getting cached engine.
208
+ reset (bool, optional): Set true to reset engine, i.e., not get cached engine. Defaults to False.
209
+ """
210
+
211
+ def get_token_struct(token: str) -> bytes:
212
+ """Convert token string to token byte struct for use in connection string
213
+
214
+ Args:
215
+ token (str): Token as string
216
+
217
+ Returns:
218
+ (bytes): Token as bytes
219
+ """
220
+ tokenb = bytes(token, "UTF-8")
221
+ exptoken = b""
222
+ for i in tokenb:
223
+ exptoken += bytes({i})
224
+ exptoken += bytes(1)
225
+
226
+ tokenstruct = struct.pack("=i", len(exptoken)) + exptoken
227
+
228
+ return tokenstruct
229
+
230
+ if conn_string is None or conn_string == "":
231
+ conn_string = self.conn_string
232
+
233
+ if not conn_string == self.conn_string:
234
+ reset = True
235
+
236
+ if token == "":
237
+ token = self.authenticator.get_token()
238
+
239
+ if reset:
240
+ self.reset_engine()
241
+
242
+ if self.Engine is None:
243
+ if not isinstance(conn_string, str) and len(conn_string) > 0:
244
+ raise TypeError("Not able to create engine without connection string.")
245
+ SQL_COPT_SS_ACCESS_TOKEN = 1256
246
+ self.Engine = create_engine(
247
+ URL.create("mssql+pyodbc", query={"odbc_connect": conn_string}),
248
+ connect_args={
249
+ "attrs_before": {SQL_COPT_SS_ACCESS_TOKEN: get_token_struct(token)},
250
+ "timeout": 60,
251
+ },
252
+ poolclass=QueuePool,
253
+ pool_size=10,
254
+ max_overflow=5,
255
+ pool_timeout=30,
256
+ pool_recycle=1800,
257
+ query_cache_size=1200,
258
+ )
259
+
260
+ return self.Engine
@@ -0,0 +1,28 @@
1
+ [project]
2
+ name = "eq-sql-connector"
3
+ version = "0.1.0"
4
+ description = "SQL Database connector to connect to public client app registrations using delegated permissions (MSAL)."
5
+ authors = [{ name = "Åsmund Våge Fannemel", email = "asmf@equinor.com" }]
6
+ license = { text = "MIT" }
7
+ readme = "README.md"
8
+ requires-python = ">=3.10,<4.0"
9
+ dependencies = [
10
+ "pandas (>=2.3.2,<3.0.0)",
11
+ "sqlalchemy (>=2.0.43,<3.0.0)",
12
+ "pyodbc (>=5.2.0,<6.0.0)",
13
+ "msal-bearer (>=1.4.3,<2.0.0)",
14
+ ]
15
+
16
+ [tool.poetry]
17
+
18
+ [tool.poetry.group.test.dependencies]
19
+ pytest = "^7.4.0"
20
+ pytest-cov = "^4.1.0"
21
+
22
+ [tool.poetry.group.dev.dependencies]
23
+ black = "^25.1.0"
24
+ pre-commit = "^4.3.0"
25
+
26
+ [build-system]
27
+ requires = ["poetry-core>=2.0.0,<3.0.0"]
28
+ build-backend = "poetry.core.masonry.api"