mssql-python 0.5.0__cp313-cp313-macosx_15_0_universal2.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.

Files changed (46) hide show
  1. mssql_python/__init__.py +69 -0
  2. mssql_python/bcp_options.py +121 -0
  3. mssql_python/connection.py +203 -0
  4. mssql_python/connection_mac.py +327 -0
  5. mssql_python/constants.py +118 -0
  6. mssql_python/cursor.py +726 -0
  7. mssql_python/cursor_mac.py +734 -0
  8. mssql_python/db_connection.py +41 -0
  9. mssql_python/ddbc_bindings.cp313-arm64.so +0 -0
  10. mssql_python/ddbc_bindings.py +44 -0
  11. mssql_python/exceptions.py +650 -0
  12. mssql_python/helpers.py +111 -0
  13. mssql_python/libs/LICENSING +19 -0
  14. mssql_python/libs/arm64/1033/msodbcsqlr18.rll +0 -0
  15. mssql_python/libs/arm64/msodbcdiag18.dll +0 -0
  16. mssql_python/libs/arm64/msodbcsql18.dll +0 -0
  17. mssql_python/libs/arm64/mssql-auth.dll +0 -0
  18. mssql_python/libs/macos/lib/libltdl.7.dylib +0 -0
  19. mssql_python/libs/macos/lib/libmsodbcsql.18.dylib +0 -0
  20. mssql_python/libs/macos/lib/libodbc.2.dylib +0 -0
  21. mssql_python/libs/macos/lib/libodbccr.2.dylib +0 -0
  22. mssql_python/libs/macos/lib/libodbcinst.2.dylib +0 -0
  23. mssql_python/libs/macos/share/doc/msodbcsql18/LICENSE.txt +101 -0
  24. mssql_python/libs/macos/share/doc/msodbcsql18/RELEASE_NOTES +465 -0
  25. mssql_python/libs/macos/share/msodbcsql18/resources/en_US/msodbcsqlr18.rll +0 -0
  26. mssql_python/libs/x64/1033/msodbcsqlr18.rll +0 -0
  27. mssql_python/libs/x64/MICROSOFT_ODBC_DRIVER_FOR_SQL_SERVER_LICENSE.txt +76 -0
  28. mssql_python/libs/x64/MICROSOFT_VISUAL_STUDIO_LICENSE.txt +54 -0
  29. mssql_python/libs/x64/msodbcdiag18.dll +0 -0
  30. mssql_python/libs/x64/msodbcsql18.dll +0 -0
  31. mssql_python/libs/x64/mssql-auth.dll +0 -0
  32. mssql_python/libs/x86/1033/msodbcsqlr18.rll +0 -0
  33. mssql_python/libs/x86/msodbcdiag18.dll +0 -0
  34. mssql_python/libs/x86/msodbcsql18.dll +0 -0
  35. mssql_python/libs/x86/mssql-auth.dll +0 -0
  36. mssql_python/logging_config.py +65 -0
  37. mssql_python/mssql_python.pyi +192 -0
  38. mssql_python/msvcp140.dll +0 -0
  39. mssql_python/pooling.py +29 -0
  40. mssql_python/testing_ddbc_bindings.py +463 -0
  41. mssql_python/type.py +107 -0
  42. mssql_python-0.5.0.dist-info/METADATA +46 -0
  43. mssql_python-0.5.0.dist-info/RECORD +46 -0
  44. mssql_python-0.5.0.dist-info/WHEEL +5 -0
  45. mssql_python-0.5.0.dist-info/licenses/LICENSE +47 -0
  46. mssql_python-0.5.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,69 @@
1
+ """
2
+ Copyright (c) Microsoft Corporation.
3
+ Licensed under the MIT license.
4
+ This module initializes the mssql_python package.
5
+ """
6
+
7
+ # Exceptions
8
+ # https://www.python.org/dev/peps/pep-0249/#exceptions
9
+ from .exceptions import (
10
+ Warning,
11
+ Error,
12
+ InterfaceError,
13
+ DatabaseError,
14
+ DataError,
15
+ OperationalError,
16
+ IntegrityError,
17
+ InternalError,
18
+ ProgrammingError,
19
+ NotSupportedError,
20
+ )
21
+
22
+ # Type Objects
23
+ from .type import (
24
+ Date,
25
+ Time,
26
+ Timestamp,
27
+ DateFromTicks,
28
+ TimeFromTicks,
29
+ TimestampFromTicks,
30
+ Binary,
31
+ STRING,
32
+ BINARY,
33
+ NUMBER,
34
+ DATETIME,
35
+ ROWID,
36
+ )
37
+
38
+ # Connection Objects
39
+ from .db_connection import connect, Connection
40
+
41
+ # Cursor Objects
42
+ from .cursor import Cursor
43
+
44
+ # Logging Configuration
45
+ from .logging_config import setup_logging, get_logger
46
+
47
+ # Constants
48
+ from .constants import ConstantsDDBC
49
+
50
+ # GLOBALS
51
+ # Read-Only
52
+ apilevel = "2.0"
53
+ paramstyle = "qmark"
54
+ threadsafety = 1
55
+
56
+ from .pooling import PoolingManager
57
+ def pooling(max_size=100, idle_timeout=600):
58
+ # """
59
+ # Enable connection pooling with the specified parameters.
60
+
61
+ # Args:
62
+ # max_size (int): Maximum number of connections in the pool.
63
+ # idle_timeout (int): Time in seconds before idle connections are closed.
64
+
65
+ # Returns:
66
+ # None
67
+ # """
68
+ PoolingManager.enable(max_size, idle_timeout)
69
+
@@ -0,0 +1,121 @@
1
+ from dataclasses import dataclass, field
2
+ from typing import List, Optional, Literal
3
+
4
+
5
+ @dataclass
6
+ class ColumnFormat:
7
+ """
8
+ Represents the format of a column in a bulk copy operation.
9
+ Attributes:
10
+ prefix_len (int): Option: (format_file) or (prefix_len, data_len).
11
+ The length of the prefix for fixed-length data types. Must be non-negative.
12
+ data_len (int): Option: (format_file) or (prefix_len, data_len).
13
+ The length of the data. Must be non-negative.
14
+ field_terminator (Optional[bytes]): Option: (-t). The field terminator string.
15
+ e.g., b',' for comma-separated values.
16
+ row_terminator (Optional[bytes]): Option: (-r). The row terminator string.
17
+ e.g., b'\\n' for newline-terminated rows.
18
+ server_col (int): Option: (format_file) or (server_col). The 1-based column number
19
+ in the SQL Server table. Defaults to 1, representing the first column.
20
+ Must be a positive integer.
21
+ file_col (int): Option: (format_file) or (file_col). The 1-based column number
22
+ in the data file. Defaults to 1, representing the first column.
23
+ Must be a positive integer.
24
+ """
25
+
26
+ prefix_len: int
27
+ data_len: int
28
+ field_terminator: Optional[bytes] = None
29
+ row_terminator: Optional[bytes] = None
30
+ server_col: int = 1
31
+ file_col: int = 1
32
+
33
+ def __post_init__(self):
34
+ if self.prefix_len < 0:
35
+ raise ValueError("prefix_len must be a non-negative integer.")
36
+ if self.data_len < 0:
37
+ raise ValueError("data_len must be a non-negative integer.")
38
+ if self.server_col <= 0:
39
+ raise ValueError("server_col must be a positive integer (1-based).")
40
+ if self.file_col <= 0:
41
+ raise ValueError("file_col must be a positive integer (1-based).")
42
+ if self.field_terminator is not None and not isinstance(
43
+ self.field_terminator, bytes
44
+ ):
45
+ raise TypeError("field_terminator must be bytes or None.")
46
+ if self.row_terminator is not None and not isinstance(
47
+ self.row_terminator, bytes
48
+ ):
49
+ raise TypeError("row_terminator must be bytes or None.")
50
+
51
+
52
+ @dataclass
53
+ class BCPOptions:
54
+ """
55
+ Represents the options for a bulk copy operation.
56
+ Attributes:
57
+ direction (Literal[str]): 'in' or 'out'. Option: (-i or -o).
58
+ data_file (str): The data file. Option: (positional argument).
59
+ error_file (Optional[str]): The error file. Option: (-e).
60
+ format_file (Optional[str]): The format file to use for 'in'/'out'. Option: (-f).
61
+ batch_size (Optional[int]): The batch size. Option: (-b).
62
+ max_errors (Optional[int]): The maximum number of errors allowed. Option: (-m).
63
+ first_row (Optional[int]): The first row to process. Option: (-F).
64
+ last_row (Optional[int]): The last row to process. Option: (-L).
65
+ code_page (Optional[str]): The code page. Option: (-C).
66
+ keep_identity (bool): Keep identity values. Option: (-E).
67
+ keep_nulls (bool): Keep null values. Option: (-k).
68
+ hints (Optional[str]): Additional hints. Option: (-h).
69
+ bulk_mode (str): Bulk mode ('native', 'char', 'unicode'). Option: (-n, -c, -w).
70
+ Defaults to "native".
71
+ columns (List[ColumnFormat]): Column formats.
72
+ """
73
+
74
+ direction: Literal["in", "out"]
75
+ data_file: str # data_file is mandatory for 'in' and 'out'
76
+ error_file: Optional[str] = None
77
+ format_file: Optional[str] = None
78
+ # write_format_file is removed as 'format' direction is not actively supported
79
+ batch_size: Optional[int] = None
80
+ max_errors: Optional[int] = None
81
+ first_row: Optional[int] = None
82
+ last_row: Optional[int] = None
83
+ code_page: Optional[str] = None
84
+ keep_identity: bool = False
85
+ keep_nulls: bool = False
86
+ hints: Optional[str] = None
87
+ bulk_mode: Literal["native", "char", "unicode"] = "native"
88
+ columns: List[ColumnFormat] = field(default_factory=list)
89
+
90
+ def __post_init__(self):
91
+ if self.direction not in ["in", "out"]:
92
+ raise ValueError("direction must be 'in' or 'out'.")
93
+ if not self.data_file:
94
+ raise ValueError("data_file must be provided and non-empty for 'in' or 'out' directions.")
95
+ if self.error_file is None or not self.error_file: # Making error_file mandatory for in/out
96
+ raise ValueError("error_file must be provided and non-empty for 'in' or 'out' directions.")
97
+
98
+ if self.format_file is not None and not self.format_file:
99
+ raise ValueError("format_file, if provided, must not be an empty string.")
100
+ if self.batch_size is not None and self.batch_size <= 0:
101
+ raise ValueError("batch_size must be a positive integer.")
102
+ if self.max_errors is not None and self.max_errors < 0:
103
+ raise ValueError("max_errors must be a non-negative integer.")
104
+ if self.first_row is not None and self.first_row <= 0:
105
+ raise ValueError("first_row must be a positive integer.")
106
+ if self.last_row is not None and self.last_row <= 0:
107
+ raise ValueError("last_row must be a positive integer.")
108
+ if self.last_row is not None and self.first_row is None:
109
+ raise ValueError("first_row must be specified if last_row is specified.")
110
+ if (
111
+ self.first_row is not None
112
+ and self.last_row is not None
113
+ and self.last_row < self.first_row
114
+ ):
115
+ raise ValueError("last_row must be greater than or equal to first_row.")
116
+ if self.code_page is not None and not self.code_page:
117
+ raise ValueError("code_page, if provided, must not be an empty string.")
118
+ if self.hints is not None and not self.hints:
119
+ raise ValueError("hints, if provided, must not be an empty string.")
120
+ if self.bulk_mode not in ["native", "char", "unicode"]:
121
+ raise ValueError("bulk_mode must be 'native', 'char', or 'unicode'.")
@@ -0,0 +1,203 @@
1
+ """
2
+ Copyright (c) Microsoft Corporation.
3
+ Licensed under the MIT license.
4
+ This module defines the Connection class, which is used to manage a connection to a database.
5
+ The class provides methods to establish a connection, create cursors, commit transactions,
6
+ roll back transactions, and close the connection.
7
+ """
8
+ import ctypes
9
+ from mssql_python.cursor import Cursor
10
+ from mssql_python.logging_config import get_logger, ENABLE_LOGGING
11
+ from mssql_python.constants import ConstantsDDBC as ddbc_sql_const
12
+ from mssql_python.helpers import add_driver_to_connection_str, check_error
13
+ from mssql_python import ddbc_bindings
14
+ from mssql_python.pooling import PoolingManager
15
+
16
+ logger = get_logger()
17
+
18
+
19
+ class Connection:
20
+ """
21
+ A class to manage a connection to a database, compliant with DB-API 2.0 specifications.
22
+
23
+ This class provides methods to establish a connection to a database, create cursors,
24
+ commit transactions, roll back transactions, and close the connection. It is designed
25
+ to be used in a context where database operations are required, such as executing queries
26
+ and fetching results.
27
+
28
+ Methods:
29
+ __init__(database: str) -> None:
30
+ connect_to_db() -> None:
31
+ cursor() -> Cursor:
32
+ commit() -> None:
33
+ rollback() -> None:
34
+ close() -> None:
35
+ """
36
+
37
+ def __init__(self, connection_str: str = "", autocommit: bool = False, attrs_before: dict = None, **kwargs) -> None:
38
+ """
39
+ Initialize the connection object with the specified connection string and parameters.
40
+
41
+ Args:
42
+ - connection_str (str): The connection string to connect to.
43
+ - autocommit (bool): If True, causes a commit to be performed after each SQL statement.
44
+ **kwargs: Additional key/value pairs for the connection string.
45
+ Not including below properties since we are driver doesn't support this:
46
+
47
+ Returns:
48
+ None
49
+
50
+ Raises:
51
+ ValueError: If the connection string is invalid or connection fails.
52
+
53
+ This method sets up the initial state for the connection object,
54
+ preparing it for further operations such as connecting to the
55
+ database, executing queries, etc.
56
+ """
57
+ self.connection_str = self._construct_connection_string(
58
+ connection_str, **kwargs
59
+ )
60
+ self._attrs_before = attrs_before or {}
61
+ self._pooling = PoolingManager.is_enabled()
62
+ self._conn = ddbc_bindings.Connection(self.connection_str, self._pooling, self._attrs_before)
63
+ self.setautocommit(autocommit)
64
+
65
+ def _construct_connection_string(self, connection_str: str = "", **kwargs) -> str:
66
+ """
67
+ Construct the connection string by concatenating the connection string
68
+ with key/value pairs from kwargs.
69
+
70
+ Args:
71
+ connection_str (str): The base connection string.
72
+ **kwargs: Additional key/value pairs for the connection string.
73
+
74
+ Returns:
75
+ str: The constructed connection string.
76
+ """
77
+ # Add the driver attribute to the connection string
78
+ conn_str = add_driver_to_connection_str(connection_str)
79
+
80
+ # Add additional key-value pairs to the connection string
81
+ for key, value in kwargs.items():
82
+ if key.lower() == "host" or key.lower() == "server":
83
+ key = "Server"
84
+ elif key.lower() == "user" or key.lower() == "uid":
85
+ key = "Uid"
86
+ elif key.lower() == "password" or key.lower() == "pwd":
87
+ key = "Pwd"
88
+ elif key.lower() == "database":
89
+ key = "Database"
90
+ elif key.lower() == "encrypt":
91
+ key = "Encrypt"
92
+ elif key.lower() == "trust_server_certificate":
93
+ key = "TrustServerCertificate"
94
+ else:
95
+ continue
96
+ conn_str += f"{key}={value};"
97
+
98
+ if ENABLE_LOGGING:
99
+ logger.info("Final connection string: %s", conn_str)
100
+
101
+ return conn_str
102
+
103
+ @property
104
+ def autocommit(self) -> bool:
105
+ """
106
+ Return the current autocommit mode of the connection.
107
+ Returns:
108
+ bool: True if autocommit is enabled, False otherwise.
109
+ """
110
+ return self._conn.get_autocommit()
111
+
112
+ @autocommit.setter
113
+ def autocommit(self, value: bool) -> None:
114
+ """
115
+ Set the autocommit mode of the connection.
116
+ Args:
117
+ value (bool): True to enable autocommit, False to disable it.
118
+ Returns:
119
+ None
120
+ """
121
+ self.setautocommit(value)
122
+ if ENABLE_LOGGING:
123
+ logger.info("Autocommit mode set to %s.", value)
124
+
125
+ def setautocommit(self, value: bool = True) -> None:
126
+ """
127
+ Set the autocommit mode of the connection.
128
+ Args:
129
+ value (bool): True to enable autocommit, False to disable it.
130
+ Returns:
131
+ None
132
+ Raises:
133
+ DatabaseError: If there is an error while setting the autocommit mode.
134
+ """
135
+ self._conn.set_autocommit(value)
136
+
137
+ def cursor(self) -> Cursor:
138
+ """
139
+ Return a new Cursor object using the connection.
140
+
141
+ This method creates and returns a new cursor object that can be used to
142
+ execute SQL queries and fetch results. The cursor is associated with the
143
+ current connection and allows interaction with the database.
144
+
145
+ Returns:
146
+ Cursor: A new cursor object for executing SQL queries.
147
+
148
+ Raises:
149
+ DatabaseError: If there is an error while creating the cursor.
150
+ InterfaceError: If there is an error related to the database interface.
151
+ """
152
+ return Cursor(self)
153
+
154
+ def commit(self) -> None:
155
+ """
156
+ Commit the current transaction.
157
+
158
+ This method commits the current transaction to the database, making all
159
+ changes made during the transaction permanent. It should be called after
160
+ executing a series of SQL statements that modify the database to ensure
161
+ that the changes are saved.
162
+
163
+ Raises:
164
+ DatabaseError: If there is an error while committing the transaction.
165
+ """
166
+ # Commit the current transaction
167
+ self._conn.commit()
168
+ if ENABLE_LOGGING:
169
+ logger.info("Transaction committed successfully.")
170
+
171
+ def rollback(self) -> None:
172
+ """
173
+ Roll back the current transaction.
174
+
175
+ This method rolls back the current transaction, undoing all changes made
176
+ during the transaction. It should be called if an error occurs during the
177
+ transaction or if the changes should not be saved.
178
+
179
+ Raises:
180
+ DatabaseError: If there is an error while rolling back the transaction.
181
+ """
182
+ # Roll back the current transaction
183
+ self._conn.rollback()
184
+ if ENABLE_LOGGING:
185
+ logger.info("Transaction rolled back successfully.")
186
+
187
+ def close(self) -> None:
188
+ """
189
+ Close the connection now (rather than whenever .__del__() is called).
190
+
191
+ This method closes the connection to the database, releasing any resources
192
+ associated with it. After calling this method, the connection object should
193
+ not be used for any further operations. The same applies to all cursor objects
194
+ trying to use the connection. Note that closing a connection without committing
195
+ the changes first will cause an implicit rollback to be performed.
196
+
197
+ Raises:
198
+ DatabaseError: If there is an error while closing the connection.
199
+ """
200
+ # Close the connection
201
+ self._conn.close()
202
+ if ENABLE_LOGGING:
203
+ logger.info("Connection closed successfully.")