mssql-python 1.0.0a0__cp313-cp313-win_amd64.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.

Potentially problematic release.


This version of mssql-python might be problematic. Click here for more details.

@@ -0,0 +1,31 @@
1
+ from .constants import (
2
+ ConstantsODBC
3
+ )
4
+
5
+ # GLOBALS
6
+ # Read-Only
7
+ apilevel = '2.0'
8
+ paramstyle = 'qmark'
9
+ threadsafety = 1
10
+
11
+ # Exceptions
12
+ # https://www.python.org/dev/peps/pep-0249/#exceptions
13
+ from .exceptions import (
14
+ Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError,
15
+ IntegrityError, InternalError, ProgrammingError, NotSupportedError
16
+ )
17
+
18
+ # Type Objects
19
+ from .type import (
20
+ Date, Time, Timestamp, DateFromTicks, TimeFromTicks, TimestampFromTicks, Binary,
21
+ STRING, BINARY, NUMBER, DATETIME, ROWID
22
+ )
23
+
24
+ # Connection Objects
25
+ from .connection import Connection
26
+ from .db_connection import connect
27
+
28
+ # Cursor Objects
29
+ from .cursor import Cursor
30
+
31
+ from .logging_config import setup_logging, get_logger
@@ -0,0 +1,302 @@
1
+ import ctypes
2
+ from mssql_python.cursor import Cursor
3
+ from mssql_python.logging_config import get_logger, ENABLE_LOGGING
4
+ from mssql_python.constants import ConstantsODBC as odbc_sql_const
5
+ from mssql_python.helpers import add_driver_to_connection_str, check_error
6
+ import os
7
+ from mssql_python import ddbc_bindings
8
+
9
+ logger = get_logger()
10
+
11
+ class Connection:
12
+ """
13
+ A class to manage a connection to a database, compliant with DB-API 2.0 specifications.
14
+
15
+ This class provides methods to establish a connection to a database, create cursors,
16
+ commit transactions, roll back transactions, and close the connection. It is designed
17
+ to be used in a context where database operations are required, such as executing queries
18
+ and fetching results.
19
+
20
+ Methods:
21
+ __init__(database: str) -> None:
22
+ connect_to_db() -> None:
23
+ cursor() -> Cursor:
24
+ commit() -> None:
25
+ rollback() -> None:
26
+ close() -> None:
27
+ """
28
+
29
+ def __init__(self, connection_str: str, autocommit: bool = False, **kwargs) -> None:
30
+ """
31
+ Initialize the connection object with the specified connection string and parameters.
32
+
33
+ Args:
34
+ - connection_str (str): The connection string to connect to.
35
+ - autocommit (bool): If True, causes a commit to be performed after each SQL statement.
36
+ **kwargs: Additional key/value pairs for the connection string.
37
+ Not including below properties since we are driver doesn't support this:
38
+
39
+ Returns:
40
+ None
41
+
42
+ Raises:
43
+ ValueError: If the connection string is invalid or connection fails.
44
+
45
+ This method sets up the initial state for the connection object,
46
+ preparing it for further operations such as connecting to the database, executing queries, etc.
47
+ """
48
+ self.henv = ctypes.c_void_p()
49
+ self.hdbc = ctypes.c_void_p()
50
+ self.connection_str = self._construct_connection_string(connection_str, **kwargs)
51
+ self._initializer()
52
+ self._autocommit = autocommit
53
+ self.setautocommit(autocommit)
54
+
55
+ def _construct_connection_string(self, connection_str: str, **kwargs) -> str:
56
+ """
57
+ Construct the connection string by concatenating the connection string with key/value pairs from kwargs.
58
+
59
+ Args:
60
+ connection_str (str): The base connection string.
61
+ **kwargs: Additional key/value pairs for the connection string.
62
+
63
+ Returns:
64
+ str: The constructed connection string.
65
+ """
66
+ # Add the driver attribute to the connection string
67
+ conn_str = add_driver_to_connection_str(connection_str)
68
+ # Add additional key-value pairs to the connection string
69
+ for key, value in kwargs.items():
70
+ if key.lower() == "host":
71
+ key = "Server"
72
+ elif key.lower() == "user":
73
+ key = "Uid"
74
+ elif key.lower() == "password":
75
+ key = "Pwd"
76
+ elif key.lower() == "database":
77
+ key = "Database"
78
+ elif key.lower() == "encrypt":
79
+ key = "Encrypt"
80
+ elif key.lower() == "trust_server_certificate":
81
+ key = "TrustServerCertificate"
82
+ else:
83
+ continue
84
+ conn_str += f"{key}={value};"
85
+ return conn_str
86
+
87
+ def _initializer(self) -> None:
88
+ """
89
+ Initialize the environment and connection handles.
90
+
91
+ This method is responsible for setting up the environment and connection
92
+ handles, allocating memory for them, and setting the necessary attributes.
93
+ It should be called before establishing a connection to the database.
94
+ """
95
+ self._allocate_environment_handle()
96
+ self._set_environment_attributes()
97
+ self._allocate_connection_handle()
98
+ self._set_connection_attributes()
99
+ self._connect_to_db()
100
+
101
+ def _allocate_environment_handle(self):
102
+ """
103
+ Allocate the environment handle.
104
+ """
105
+ ret = ddbc_bindings.DDBCSQLAllocHandle(
106
+ odbc_sql_const.SQL_HANDLE_ENV.value, #SQL environment handle type
107
+ 0, # SQL input handle
108
+ ctypes.cast(ctypes.pointer(self.henv), ctypes.c_void_p).value # SQL output handle pointer
109
+ )
110
+ check_error(odbc_sql_const.SQL_HANDLE_ENV.value, self.henv.value, ret)
111
+
112
+ def _set_environment_attributes(self):
113
+ """
114
+ Set the environment attributes.
115
+ """
116
+ ret = ddbc_bindings.DDBCSQLSetEnvAttr(
117
+ self.henv.value, # Environment handle
118
+ odbc_sql_const.SQL_ATTR_ODBC_VERSION.value, # Attribute
119
+ odbc_sql_const.SQL_OV_ODBC3_80.value, # String Length
120
+ 0 # Null-terminated string
121
+ )
122
+ check_error(odbc_sql_const.SQL_HANDLE_ENV.value, self.henv.value, ret)
123
+
124
+ def _allocate_connection_handle(self):
125
+ """
126
+ Allocate the connection handle.
127
+ """
128
+ ret = ddbc_bindings.DDBCSQLAllocHandle(
129
+ odbc_sql_const.SQL_HANDLE_DBC.value, # SQL connection handle type
130
+ self.henv.value, # SQL environment handle
131
+ ctypes.cast(ctypes.pointer(self.hdbc), ctypes.c_void_p).value # SQL output handle pointer
132
+ )
133
+ check_error(odbc_sql_const.SQL_HANDLE_DBC.value, self.hdbc.value, ret)
134
+
135
+ def _set_connection_attributes(self):
136
+ """
137
+ Set the connection attributes before connecting.
138
+ """
139
+ if self.autocommit:
140
+ ret = ddbc_bindings.DDBCSQLSetConnectAttr(
141
+ self.hdbc.value,
142
+ odbc_sql_const.SQL_ATTR_AUTOCOMMIT.value,
143
+ odbc_sql_const.SQL_AUTOCOMMIT_ON.value,
144
+ 0
145
+ )
146
+ check_error(odbc_sql_const.SQL_HANDLE_DBC.value, self.hdbc.value, ret)
147
+
148
+ def _connect_to_db(self) -> None:
149
+ """
150
+ Establish a connection to the database.
151
+
152
+ This method is responsible for creating a connection to the specified database.
153
+ It does not take any arguments and does not return any value. The connection
154
+ details such as database name, user credentials, host, and port should be
155
+ configured within the class or passed during the class instantiation.
156
+
157
+ Raises:
158
+ DatabaseError: If there is an error while trying to connect to the database.
159
+ InterfaceError: If there is an error related to the database interface.
160
+ """
161
+ if ENABLE_LOGGING:
162
+ logger.info("Connecting to the database")
163
+ ret = ddbc_bindings.DDBCSQLDriverConnect(
164
+ self.hdbc.value, # Connection handle
165
+ 0, # Window handle
166
+ self.connection_str # Connection string
167
+ )
168
+ check_error(odbc_sql_const.SQL_HANDLE_DBC.value, self.hdbc.value, ret)
169
+ if ENABLE_LOGGING:
170
+ logger.info("Connection established successfully.")
171
+
172
+ @property
173
+ def autocommit(self) -> bool:
174
+ """
175
+ Return the current autocommit mode of the connection.
176
+ Returns:
177
+ bool: True if autocommit is enabled, False otherwise.
178
+ """
179
+ autocommit_mode = ddbc_bindings.DDBCSQLGetConnectionAttr(
180
+ self.hdbc.value, # Connection handle
181
+ odbc_sql_const.SQL_ATTR_AUTOCOMMIT.value, # Attribute
182
+ )
183
+ check_error(odbc_sql_const.SQL_HANDLE_DBC.value, self.hdbc.value, autocommit_mode)
184
+ return autocommit_mode == odbc_sql_const.SQL_AUTOCOMMIT_ON.value
185
+
186
+ @autocommit.setter
187
+ def autocommit(self, value: bool) -> None:
188
+ """
189
+ Set the autocommit mode of the connection.
190
+ Args:
191
+ value (bool): True to enable autocommit, False to disable it.
192
+ Returns:
193
+ None
194
+ Raises:
195
+ DatabaseError: If there is an error while setting the autocommit mode.
196
+ """
197
+ ret = ddbc_bindings.DDBCSQLSetConnectAttr(
198
+ self.hdbc.value, # Connection handle
199
+ odbc_sql_const.SQL_ATTR_AUTOCOMMIT.value, # Attribute
200
+ odbc_sql_const.SQL_AUTOCOMMIT_ON.value if value else odbc_sql_const.SQL_AUTOCOMMIT_OFF.value, # Value
201
+ 0 # String length
202
+ )
203
+ check_error(odbc_sql_const.SQL_HANDLE_DBC.value, self.hdbc.value, ret)
204
+ self._autocommit = value
205
+ if ENABLE_LOGGING:
206
+ logger.info("Autocommit mode set to %s.", value)
207
+
208
+ def setautocommit(self, value: bool = True) -> None:
209
+ """
210
+ Set the autocommit mode of the connection.
211
+ Args:
212
+ value (bool): True to enable autocommit, False to disable it.
213
+ Returns:
214
+ None
215
+ Raises:
216
+ DatabaseError: If there is an error while setting the autocommit mode.
217
+ """
218
+ self.autocommit = value
219
+
220
+ def cursor(self) -> Cursor:
221
+ """
222
+ Return a new Cursor object using the connection.
223
+
224
+ This method creates and returns a new cursor object that can be used to
225
+ execute SQL queries and fetch results. The cursor is associated with the
226
+ current connection and allows interaction with the database.
227
+
228
+ Returns:
229
+ Cursor: A new cursor object for executing SQL queries.
230
+
231
+ Raises:
232
+ DatabaseError: If there is an error while creating the cursor.
233
+ InterfaceError: If there is an error related to the database interface.
234
+ """
235
+ return Cursor(self)
236
+
237
+ def commit(self) -> None:
238
+ """
239
+ Commit the current transaction.
240
+
241
+ This method commits the current transaction to the database, making all
242
+ changes made during the transaction permanent. It should be called after
243
+ executing a series of SQL statements that modify the database to ensure
244
+ that the changes are saved.
245
+
246
+ Raises:
247
+ DatabaseError: If there is an error while committing the transaction.
248
+ """
249
+ # Commit the current transaction
250
+ ret = ddbc_bindings.DDBCSQLEndTran(
251
+ odbc_sql_const.SQL_HANDLE_DBC.value, # Handle type
252
+ self.hdbc.value, # Connection handle
253
+ odbc_sql_const.SQL_COMMIT.value # Commit the transaction
254
+ )
255
+ check_error(odbc_sql_const.SQL_HANDLE_DBC.value, self.hdbc.value, ret)
256
+ if ENABLE_LOGGING:
257
+ logger.info("Transaction committed successfully.")
258
+
259
+ def rollback(self) -> None:
260
+ """
261
+ Roll back the current transaction.
262
+
263
+ This method rolls back the current transaction, undoing all changes made
264
+ during the transaction. It should be called if an error occurs during the
265
+ transaction or if the changes should not be saved.
266
+
267
+ Raises:
268
+ DatabaseError: If there is an error while rolling back the transaction.
269
+ """
270
+ # Roll back the current transaction
271
+ ret = ddbc_bindings.DDBCSQLEndTran(
272
+ odbc_sql_const.SQL_HANDLE_DBC.value, # Handle type
273
+ self.hdbc.value, # Connection handle
274
+ odbc_sql_const.SQL_ROLLBACK.value # Roll back the transaction
275
+ )
276
+ check_error(odbc_sql_const.SQL_HANDLE_DBC.value, self.hdbc.value, ret)
277
+ if ENABLE_LOGGING:
278
+ logger.info("Transaction rolled back successfully.")
279
+
280
+ def close(self) -> None:
281
+ """
282
+ Close the connection now (rather than whenever .__del__() is called).
283
+
284
+ This method closes the connection to the database, releasing any resources
285
+ associated with it. After calling this method, the connection object should
286
+ not be used for any further operations. The same applies to all cursor objects
287
+ trying to use the connection. Note that closing a connection without committing
288
+ the changes first will cause an implicit rollback to be performed.
289
+
290
+ Raises:
291
+ DatabaseError: If there is an error while closing the connection.
292
+ """
293
+ # Disconnect from the database
294
+ ret = ddbc_bindings.DDBCSQLDisconnect(self.hdbc.value)
295
+ check_error(odbc_sql_const.SQL_HANDLE_DBC.value, self.hdbc.value, ret)
296
+
297
+ # Free the connection handle
298
+ ret = ddbc_bindings.DDBCSQLFreeHandle(odbc_sql_const.SQL_HANDLE_DBC.value, self.hdbc.value)
299
+ check_error(odbc_sql_const.SQL_HANDLE_DBC.value, self.hdbc.value, ret)
300
+
301
+ if ENABLE_LOGGING:
302
+ logger.info("Connection closed successfully.")
@@ -0,0 +1,108 @@
1
+ from enum import Enum
2
+
3
+ class ConstantsODBC(Enum):
4
+ SQL_HANDLE_ENV = 1
5
+ SQL_HANDLE_DBC = 2
6
+ SQL_HANDLE_STMT = 3
7
+ SQL_SUCCESS = 0
8
+ SQL_SUCCESS_WITH_INFO = 1
9
+ SQL_NO_DATA = 100
10
+ SQL_STILL_EXECUTING = 2
11
+ SQL_NTS = -3
12
+ SQL_DRIVER_NOPROMPT = 0
13
+ SQL_ATTR_ASYNC_DBC_EVENT = 119
14
+ SQL_IS_INTEGER = -6
15
+ SQL_ATTR_ASYNC_DBC_FUNCTIONS_ENABLE = 117
16
+ SQL_OV_ODBC3_80 = 380
17
+ SQL_ATTR_ODBC_VERSION = 200
18
+ SQL_ATTR_ASYNC_ENABLE = 4
19
+ SQL_ATTR_ASYNC_STMT_EVENT = 29
20
+ SQL_ERROR = -1
21
+ SQL_INVALID_HANDLE = -2
22
+ SQL_NULL_HANDLE = 0
23
+ SQL_OV_ODBC3 = 3
24
+ SQL_COMMIT = 0
25
+ SQL_ROLLBACK = 1
26
+ SQL_ATTR_AUTOCOMMIT = 102
27
+ SQL_SMALLINT = 5
28
+ SQL_CHAR = 1
29
+ SQL_WCHAR = -8
30
+ SQL_WVARCHAR = -9
31
+ SQL_BIT = -7
32
+ SQL_TINYINT = -6
33
+ SQL_BIGINT = -5
34
+ SQL_BINARY = -2
35
+ SQL_VARBINARY = -3
36
+ SQL_LONGVARBINARY = -4
37
+ SQL_LONGVARCHAR = -1
38
+ SQL_UNKNOWN_TYPE = 0
39
+ SQL_NUMERIC = 2
40
+ SQL_DECIMAL = 3
41
+ SQL_INTEGER = 4
42
+ SQL_FLOAT = 6
43
+ SQL_REAL = 7
44
+ SQL_DOUBLE = 8
45
+ SQL_DATETIME = 9
46
+ SQL_INTERVAL = 10
47
+ SQL_TIMESTAMP = 11
48
+ SQL_DATE = 9
49
+ SQL_TIME = 10
50
+ SQL_VARCHAR = 12
51
+ SQL_TYPE_DATE = 91
52
+ SQL_TYPE_TIME = 92
53
+ SQL_TYPE_TIMESTAMP = 93
54
+ SQL_TYPE_TIMESTAMP_WITH_TIMEZONE = 95
55
+ SQL_GUID = -11
56
+ SQL_XML = 241
57
+ SQL_SMALLDATETIME = 58
58
+ SQL_TIMESTAMPOFFSET = 43
59
+ SQL_DATETIME2 = 42
60
+ SQL_SMALLMONEY = 122
61
+ SQL_MONEY = 60
62
+ SQL_WLONGVARCHAR = -10
63
+ SQL_C_BIT = -7
64
+ SQL_C_TINYINT = -6
65
+ SQL_C_SBIGINT = -25
66
+ SQL_C_BINARY = -2
67
+ SQL_AUTOCOMMIT_ON = 1
68
+ SQL_AUTOCOMMIT_OFF = 0
69
+ SQL_C_VARBINARY = -3
70
+ SQL_C_LONGVARBINARY = -4
71
+ SQL_C_LONGVARCHAR = -1
72
+ SQL_C_CHAR = -8
73
+ SQL_C_NUMERIC = 2
74
+ SQL_C_DECIMAL = 3
75
+ SQL_C_LONG = 4
76
+ SQL_C_SHORT = 5
77
+ SQL_C_FLOAT = 7
78
+ SQL_C_DOUBLE = 8
79
+ SQL_C_TYPE_DATE = 91
80
+ SQL_C_TYPE_TIME = 92
81
+ SQL_C_TYPE_TIMESTAMP = 93
82
+ SQL_C_TYPE_TIMESTAMP_WITH_TIMEZONE = 95
83
+ SQL_C_GUID = -11
84
+ SQL_DESC_TYPE = 2
85
+ SQL_DESC_LENGTH = 3
86
+ SQL_DESC_NAME = 4
87
+ SQL_ATTR_ROW_ARRAY_SIZE = 27
88
+ SQL_ATTR_ROWS_FETCHED_PTR = 26
89
+ SQL_ATTR_ROW_STATUS_PTR = 25
90
+ SQL_FETCH_NEXT = 1
91
+ SQL_ROW_SUCCESS = 0
92
+ SQL_ROW_SUCCESS_WITH_INFO = 1
93
+ SQL_ROW_NOROW = 100
94
+ SQL_ATTR_CURSOR_TYPE = 6
95
+ SQL_CURSOR_FORWARD_ONLY = 0
96
+ SQL_CURSOR_STATIC = 3
97
+ SQL_CURSOR_KEYSET_DRIVEN = 2
98
+ SQL_CURSOR_DYNAMIC = 3
99
+ SQL_NULL_DATA = -1
100
+ SQL_C_DEFAULT = 99
101
+ SQL_ATTR_ROW_BIND_TYPE = 5
102
+ SQL_BIND_BY_COLUMN = 0
103
+ SQL_PARAM_INPUT = 1
104
+ SQL_PARAM_OUTPUT = 2
105
+ SQL_PARAM_INPUT_OUTPUT = 3
106
+ SQL_C_WCHAR = -8
107
+ SQL_NULLABLE = 1
108
+ SQL_MAX_NUMERIC_LEN = 16