pyodbc 5.3.0__tar.gz → 5.5.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.
Files changed (46) hide show
  1. {pyodbc-5.3.0/src/pyodbc.egg-info → pyodbc-5.5.0}/PKG-INFO +3 -3
  2. {pyodbc-5.3.0 → pyodbc-5.5.0}/pyproject.toml +3 -3
  3. {pyodbc-5.3.0 → pyodbc-5.5.0}/setup.py +2 -1
  4. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/cnxninfo.cpp +17 -0
  5. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/cnxninfo.h +3 -0
  6. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/connection.cpp +351 -30
  7. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/connection.h +30 -1
  8. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/cursor.cpp +483 -44
  9. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/cursor.h +28 -3
  10. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/dbspecific.h +1 -0
  11. pyodbc-5.5.0/src/decimal.cpp +328 -0
  12. pyodbc-5.5.0/src/decimal.h +10 -0
  13. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/errors.cpp +38 -8
  14. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/errors.h +0 -1
  15. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/getdata.cpp +155 -10
  16. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/params.cpp +818 -261
  17. {pyodbc-5.3.0 → pyodbc-5.5.0/src/pyodbc.egg-info}/PKG-INFO +3 -3
  18. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/pyodbc.h +0 -3
  19. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/pyodbc.pyi +173 -67
  20. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/pyodbcmodule.cpp +170 -37
  21. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/pyodbcmodule.h +4 -4
  22. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/row.cpp +23 -4
  23. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/textenc.cpp +15 -11
  24. {pyodbc-5.3.0 → pyodbc-5.5.0}/tests/mysql_test.py +52 -15
  25. {pyodbc-5.3.0 → pyodbc-5.5.0}/tests/postgresql_test.py +420 -17
  26. pyodbc-5.5.0/tests/sqlite_test.py +1050 -0
  27. {pyodbc-5.3.0 → pyodbc-5.5.0}/tests/sqlserver_test.py +757 -79
  28. pyodbc-5.3.0/src/decimal.cpp +0 -141
  29. pyodbc-5.3.0/src/decimal.h +0 -7
  30. pyodbc-5.3.0/tests/sqlite_test.py +0 -638
  31. {pyodbc-5.3.0 → pyodbc-5.5.0}/LICENSE.txt +0 -0
  32. {pyodbc-5.3.0 → pyodbc-5.5.0}/MANIFEST.in +0 -0
  33. {pyodbc-5.3.0 → pyodbc-5.5.0}/README.md +0 -0
  34. {pyodbc-5.3.0 → pyodbc-5.5.0}/setup.cfg +0 -0
  35. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/getdata.h +0 -0
  36. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/params.h +0 -0
  37. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/pyodbc.egg-info/SOURCES.txt +0 -0
  38. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/pyodbc.egg-info/dependency_links.txt +0 -0
  39. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/pyodbc.egg-info/top_level.txt +0 -0
  40. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/pyodbcdbg.cpp +0 -0
  41. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/resource.h +0 -0
  42. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/row.h +0 -0
  43. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/textenc.h +0 -0
  44. {pyodbc-5.3.0 → pyodbc-5.5.0}/src/wrapper.h +0 -0
  45. {pyodbc-5.3.0 → pyodbc-5.5.0}/tests/__init__.py +0 -0
  46. {pyodbc-5.3.0 → pyodbc-5.5.0}/tests/conftest.py +0 -0
@@ -1,12 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyodbc
3
- Version: 5.3.0
3
+ Version: 5.5.0
4
4
  Summary: DB API module for ODBC
5
5
  Home-page: https://github.com/mkleehammer/pyodbc
6
6
  Author-email: Michael Kleehammer <michael@kleehammer.com>
7
7
  Maintainer: Michael Kleehammer
8
8
  Maintainer-email: Michael Kleehammer <michael@kleehammer.com>
9
- License: MIT
9
+ License-Expression: MIT-0
10
10
  Project-URL: Homepage, https://github.com/mkleehammer/pyodbc
11
11
  Classifier: Development Status :: 5 - Production/Stable
12
12
  Classifier: Intended Audience :: Developers
@@ -16,7 +16,7 @@ Classifier: Operating System :: POSIX
16
16
  Classifier: Programming Language :: Python
17
17
  Classifier: Programming Language :: Python :: 3
18
18
  Classifier: Topic :: Database
19
- Requires-Python: >=3.9
19
+ Requires-Python: >=3.11
20
20
  Description-Content-Type: text/markdown
21
21
  License-File: LICENSE.txt
22
22
  Dynamic: home-page
@@ -1,8 +1,8 @@
1
1
  [project]
2
2
  name = "pyodbc"
3
- version = "5.3.0"
3
+ version = "5.5.0"
4
4
 
5
- requires-python = ">=3.9"
5
+ requires-python = ">=3.11"
6
6
  # This is used by the GitHub action that builds release artifacts using cibuildwheel.
7
7
  # cibuildwheel reads this directly:
8
8
  #
@@ -10,7 +10,7 @@ requires-python = ">=3.9"
10
10
 
11
11
  description = "DB API module for ODBC"
12
12
  readme = "README.md"
13
- license = { text = "MIT" }
13
+ license = "MIT-0"
14
14
 
15
15
  authors = [{name = "Michael Kleehammer", email="michael@kleehammer.com"}]
16
16
 
@@ -56,7 +56,7 @@ def main():
56
56
  package_dir={'': 'src'},
57
57
  package_data={'': ['pyodbc.pyi']}, # places pyodbc.pyi alongside pyodbc.{platform}.{pyd|so} in site-packages
58
58
  license='MIT-0',
59
- python_requires='>=3.9',
59
+ python_requires='>=3.11',
60
60
  classifiers=['Development Status :: 5 - Production/Stable',
61
61
  'Intended Audience :: Developers',
62
62
  'Intended Audience :: System Administrators',
@@ -116,6 +116,7 @@ def get_compiler_settings():
116
116
 
117
117
  settings['libraries'].append('odbc32')
118
118
  settings['libraries'].append('advapi32')
119
+ settings['libraries'].append('user32')
119
120
 
120
121
  elif os.environ.get("OS", '').lower().startswith('windows'):
121
122
  # Windows Cygwin (posix on windows)
@@ -93,6 +93,7 @@ static PyObject* CnxnInfo_New(Connection* cnxn)
93
93
  p->supports_describeparam = false;
94
94
  p->datetime_precision = 19; // default: "yyyy-mm-dd hh:mm:ss"
95
95
  p->need_long_data_len = false;
96
+ p->is_postgresql = false;
96
97
 
97
98
  p->varchar_maxlength = 1 * 1024 * 1024 * 1024;
98
99
  p->wvarchar_maxlength = 1 * 1024 * 1024 * 1024;
@@ -127,6 +128,22 @@ static PyObject* CnxnInfo_New(Connection* cnxn)
127
128
  if (SQL_SUCCEEDED(SQLGetInfo(cnxn->hdbc, SQL_NEED_LONG_DATA_LEN, szYN, _countof(szYN), &cch)))
128
129
  p->need_long_data_len = (szYN[0] == 'Y');
129
130
 
131
+ // psqlODBC reports "PostgreSQL" for every server it connects to. PostgreSQL numerics can
132
+ // hold NaN, Infinity, and more digits than a SQL_NUMERIC_STRUCT, which psqlODBC silently
133
+ // turns into 0 or a wrong number, so they are read as text.
134
+ // The buffer is large enough for any real name: unixODBC reads past the end of a buffer
135
+ // that a long name ("Microsoft SQL Server" is 20 characters) was truncated to fit.
136
+ char szDBMS[256];
137
+ if (SQL_SUCCEEDED(SQLGetInfo(cnxn->hdbc, SQL_DBMS_NAME, szDBMS, _countof(szDBMS), &cch)))
138
+ {
139
+ szDBMS[_countof(szDBMS) - 1] = 0;
140
+ const char* pg = "postgresql";
141
+ int i = 0;
142
+ while (pg[i] && szDBMS[i] && (szDBMS[i] | 0x20) == pg[i])
143
+ i++;
144
+ p->is_postgresql = (pg[i] == 0);
145
+ }
146
+
130
147
  GetColumnSize(cnxn, SQL_VARCHAR, &p->varchar_maxlength);
131
148
  GetColumnSize(cnxn, SQL_WVARCHAR, &p->wvarchar_maxlength);
132
149
  GetColumnSize(cnxn, SQL_VARBINARY, &p->binary_maxlength);
@@ -31,6 +31,9 @@ struct CnxnInfo
31
31
  // we'll use SQL_DATA_AT_EXEC when possible. If this is true, however, we'll need to pass the length.
32
32
  bool need_long_data_len;
33
33
 
34
+ // True if SQL_DBMS_NAME is PostgreSQL, so DECIMAL and NUMERIC default to DECIMAL_MODE_TEXT.
35
+ bool is_postgresql;
36
+
34
37
  // These are from SQLGetTypeInfo.column_size, so the char ones are in characters, not bytes.
35
38
  int varchar_maxlength;
36
39
  int wvarchar_maxlength;
@@ -59,7 +59,7 @@ static char* StrDup(const char* text) {
59
59
  }
60
60
 
61
61
 
62
- static bool Connect(PyObject* pConnectString, HDBC hdbc, long timeout, PyObject* encoding)
62
+ static bool Connect(PyObject* pConnectString, HDBC hdbc, long timeout, PyObject* encoding, SQLUSMALLINT driver_completion)
63
63
  {
64
64
  assert(PyUnicode_Check(pConnectString));
65
65
 
@@ -88,25 +88,42 @@ static bool Connect(PyObject* pConnectString, HDBC hdbc, long timeout, PyObject*
88
88
  if (!cstring.isValid())
89
89
  return false;
90
90
 
91
+ SQLHWND hwnd = 0;
92
+ #ifdef _WIN32
93
+ if (driver_completion != SQL_DRIVER_NOPROMPT)
94
+ {
95
+ hwnd = GetDesktopWindow();
96
+ if (!hwnd)
97
+ {
98
+ PyErr_SetString(OperationalError, "Failed to get desktop window handle");
99
+ return false;
100
+ }
101
+ }
102
+ #endif
103
+
91
104
  Py_BEGIN_ALLOW_THREADS
92
- ret = SQLDriverConnectW(hdbc, 0, cstring, SQL_NTS, 0, 0, 0, SQL_DRIVER_NOPROMPT);
105
+ ret = SQLDriverConnectW(hdbc, hwnd, cstring, SQL_NTS, 0, 0, 0, driver_completion);
93
106
  Py_END_ALLOW_THREADS
94
107
  if (SQL_SUCCEEDED(ret))
95
108
  return true;
96
109
 
110
+ if (ret == SQL_NO_DATA)
111
+ {
112
+ PyErr_SetString(OperationalError, "User cancelled connection request");
113
+ return false;
114
+ }
115
+
97
116
  RaiseErrorFromHandle(0, "SQLDriverConnect", hdbc, SQL_NULL_HANDLE);
98
117
 
99
118
  return false;
100
119
  }
101
120
 
102
- static bool ApplyPreconnAttrs(HDBC hdbc, SQLINTEGER ikey, PyObject *value, char *strencoding)
121
+ static bool ApplyPreconnAttrs(HDBC hdbc, SQLINTEGER ikey, PyObject *value, char *strencoding, PyObject *keepalives)
103
122
  {
104
123
  SQLRETURN ret;
105
124
  SQLPOINTER ivalue = 0;
106
125
  SQLINTEGER vallen = 0;
107
126
 
108
- SQLWChar sqlchar;
109
-
110
127
  if (PyLong_Check(value))
111
128
  {
112
129
  if (_PyLong_Sign(value) >= 0)
@@ -121,28 +138,71 @@ static bool ApplyPreconnAttrs(HDBC hdbc, SQLINTEGER ikey, PyObject *value, char
121
138
  }
122
139
  else if (PyByteArray_Check(value))
123
140
  {
124
- ivalue = (SQLPOINTER)PyByteArray_AsString(value);
141
+ // A bytearray is mutable: PyByteArray_AsString returns a pointer into its internal
142
+ // storage, which a concurrent resize (.extend(), +=, slice assignment) reallocates,
143
+ // invalidating the pointer we hand to the driver. Some drivers read the buffer late
144
+ // (during SQLDriverConnectW, after the GIL has been released), so snapshot the contents
145
+ // into an immutable bytes and keep that alive instead -- matching the bytes/str paths
146
+ // and closing the race for the bytearray case.
147
+ // https://github.com/mkleehammer/pyodbc/issues/1497
148
+ Object po(PyBytes_FromObject(value));
149
+ if (!po)
150
+ return false; // OOM
151
+ ivalue = (SQLPOINTER)PyBytes_AsString(po);
125
152
  vallen = SQL_IS_POINTER;
153
+ // PyList_Append increments the refcount, so the list owns the snapshot for as long as
154
+ // the driver needs it; po releases our own reference when it goes out of scope.
155
+ if (PyList_Append(keepalives, po)) // OOM
156
+ return false;
126
157
  }
127
158
  else if (PyBytes_Check(value))
128
159
  {
129
- ivalue = PyBytes_AsString(value);
160
+ // Keep the value alive beyond this function invocation's lifetime.
161
+ if (PyList_Append(keepalives, value)) // OOM
162
+ return false;
163
+ ivalue = (SQLPOINTER)PyBytes_AsString(value);
130
164
  vallen = SQL_IS_POINTER;
131
165
  }
132
166
  else if (PyUnicode_Check(value))
133
167
  {
134
- sqlchar.set(value, strencoding ? strencoding : "utf-16le");
135
- ivalue = sqlchar.get();
168
+ Object encoded(PyUnicode_AsEncodedString(value, strencoding ? strencoding : "utf-16le", "strict"));
169
+ if (!encoded)
170
+ return false;
171
+ // The value is passed with SQL_NTS, so it needs a NUL as wide as a character. A bytes
172
+ // object only has one NUL byte, so copy it with 4 (enough for UTF-16 or UTF-32).
173
+ Py_ssize_t cb = PyBytes_GET_SIZE(encoded.Get());
174
+ Object po(PyBytes_FromStringAndSize(0, cb + 4));
175
+ if (!po)
176
+ return false; // OOM
177
+ memcpy(PyBytes_AS_STRING(po.Get()), PyBytes_AS_STRING(encoded.Get()), (size_t)cb);
178
+ memset(PyBytes_AS_STRING(po.Get()) + cb, 0, 4);
179
+ ivalue = (SQLPOINTER)PyBytes_AS_STRING(po.Get());
136
180
  vallen = SQL_NTS;
181
+ // PyList_Append increments the refcount, so the list owns the encoded buffer for as long
182
+ // as the driver needs it; po releases our own reference when it goes out of scope.
183
+ if (PyList_Append(keepalives, po)) // OOM
184
+ return false;
137
185
  }
138
186
  else if (PySequence_Check(value))
139
187
  {
140
188
  // To allow for possibility of setting multiple attributes more than once.
141
189
  Py_ssize_t len = PySequence_Size(value);
190
+ if (len < 0)
191
+ return false;
142
192
  for (Py_ssize_t i = 0; i < len; i++)
143
193
  {
144
194
  Object v(PySequence_GetItem(value, i));
145
- if (!ApplyPreconnAttrs(hdbc, ikey, v.Get(), strencoding))
195
+ if (!v)
196
+ return false;
197
+ // Only one level of nesting is allowed (CheckAttrsVal), but the sequence could
198
+ // return something else now than when it was checked.
199
+ if (!PyLong_Check(v) && !PyByteArray_Check(v) && !PyBytes_Check(v) && !PyUnicode_Check(v))
200
+ {
201
+ RaiseErrorV(0, PyExc_TypeError, "Unsupported attrs_before type: %s",
202
+ Py_TYPE(v.Get())->tp_name);
203
+ return false;
204
+ }
205
+ if (!ApplyPreconnAttrs(hdbc, ikey, v.Get(), strencoding, keepalives))
146
206
  return false;
147
207
  }
148
208
  return true;
@@ -170,7 +230,7 @@ static bool ApplyPreconnAttrs(HDBC hdbc, SQLINTEGER ikey, PyObject *value, char
170
230
  }
171
231
 
172
232
  PyObject* Connection_New(PyObject* pConnectString, bool fAutoCommit, long timeout, bool fReadOnly,
173
- PyObject* attrs_before, PyObject* encoding)
233
+ PyObject* attrs_before, PyObject* encoding, SQLUSMALLINT driver_completion)
174
234
  {
175
235
  //
176
236
  // Allocate HDBC and connect
@@ -189,39 +249,87 @@ PyObject* Connection_New(PyObject* pConnectString, bool fAutoCommit, long timeou
189
249
  // Attributes that must be set before connecting.
190
250
  //
191
251
 
252
+ PyObject* preconn_keepalives = 0;
192
253
  if (attrs_before)
193
254
  {
255
+ // We have evidence that some drivers hold on to preconnection values longer after the
256
+ // call to SQLSetConnectAttrW has returned, so we're keeping those values alive to avoid
257
+ // a crash.
258
+ // https://github.com/mkleehammer/pyodbc/issues/1469
259
+ // https://github.com/microsoft/msphpsql/issues/1594
260
+ preconn_keepalives = PyList_New(0);
261
+ if (!preconn_keepalives)
262
+ return 0;
263
+
194
264
  Py_ssize_t pos = 0;
195
265
  PyObject* key = 0;
196
266
  PyObject* value = 0;
197
267
 
198
268
  Object encodingholder;
199
- char *strencoding = (encoding != 0) ?
200
- (PyUnicode_Check(encoding) ? PyBytes_AsString(encodingholder = PyCodec_Encode(encoding, "utf-8", "strict")) :
201
- PyBytes_Check(encoding) ? PyBytes_AsString(encoding) : 0) : 0;
269
+ char *strencoding = 0;
270
+ if (encoding && PyUnicode_Check(encoding))
271
+ {
272
+ encodingholder = PyCodec_Encode(encoding, "utf-8", "strict");
273
+ if (!encodingholder)
274
+ {
275
+ Py_DECREF(preconn_keepalives);
276
+ Py_BEGIN_ALLOW_THREADS
277
+ SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
278
+ Py_END_ALLOW_THREADS
279
+ return 0;
280
+ }
281
+ strencoding = PyBytes_AS_STRING(encodingholder.Get());
282
+ }
283
+ else if (encoding && PyBytes_Check(encoding))
284
+ {
285
+ strencoding = PyBytes_AS_STRING(encoding);
286
+ }
202
287
 
203
288
  while (PyDict_Next(attrs_before, &pos, &key, &value))
204
289
  {
205
290
  SQLINTEGER ikey = 0;
206
291
 
207
292
  if (PyLong_Check(key))
208
- ikey = (int)PyLong_AsLong(key);
209
- if (!ApplyPreconnAttrs(hdbc, ikey, value, strencoding))
210
293
  {
294
+ // Attribute IDs are SQLINTEGERs. long is 64 bits on most Unix platforms, so
295
+ // check the range rather than truncate to another attribute.
296
+ long lkey = PyLong_AsLong(key);
297
+ if (!PyErr_Occurred() && (lkey < INT_MIN || lkey > INT_MAX))
298
+ PyErr_Format(PyExc_OverflowError,
299
+ "attrs_before key %ld is outside the range of an ODBC attribute ID",
300
+ lkey);
301
+ ikey = (SQLINTEGER)lkey;
302
+ if (PyErr_Occurred())
303
+ {
304
+ Py_DECREF(preconn_keepalives);
305
+ Py_BEGIN_ALLOW_THREADS
306
+ SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
307
+ Py_END_ALLOW_THREADS
308
+ return 0;
309
+ }
310
+ }
311
+ if (!ApplyPreconnAttrs(hdbc, ikey, value, strencoding, preconn_keepalives))
312
+ {
313
+ Py_DECREF(preconn_keepalives);
211
314
  return 0;
212
315
  }
213
316
  }
214
317
  }
215
318
 
216
- if (!Connect(pConnectString, hdbc, timeout, encoding))
319
+ if (!Connect(pConnectString, hdbc, timeout, encoding, driver_completion))
217
320
  {
218
321
  // Connect has already set an exception.
219
322
  Py_BEGIN_ALLOW_THREADS
220
323
  SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
221
324
  Py_END_ALLOW_THREADS
325
+ Py_XDECREF(preconn_keepalives);
222
326
  return 0;
223
327
  }
224
328
 
329
+ // The current evidence indicates that the bug in Microsoft's driver isn't as bad as it
330
+ // could be, so we don't have to keep these objects alive until the connection is closed.
331
+ Py_XDECREF(preconn_keepalives);
332
+
225
333
  //
226
334
  // Connected, so allocate the Connection object.
227
335
  //
@@ -250,8 +358,11 @@ PyObject* Connection_New(PyObject* pConnectString, bool fAutoCommit, long timeou
250
358
  cnxn->maxwrite = 0;
251
359
  cnxn->timeout = 0;
252
360
  cnxn->map_sqltype_to_converter = 0;
361
+ cnxn->readvar_initsize = 4096;
362
+ cnxn->compat_diagrec_byte_length = false;
253
363
 
254
364
  cnxn->attrs_before = attrs_before_o.Detach();
365
+ cnxn->decimal_mode = DECIMAL_MODE_BINARY;
255
366
 
256
367
  // This is an inefficient default, but should work all the time. When we are offered
257
368
  // single-byte text we don't actually know what the encoding is. For example, with SQL
@@ -341,6 +452,7 @@ PyObject* Connection_New(PyObject* pConnectString, bool fAutoCommit, long timeou
341
452
  cnxn->varchar_maxlength = p->varchar_maxlength;
342
453
  cnxn->wvarchar_maxlength = p->wvarchar_maxlength;
343
454
  cnxn->binary_maxlength = p->binary_maxlength;
455
+ cnxn->decimal_mode = p->is_postgresql ? DECIMAL_MODE_TEXT : DECIMAL_MODE_BINARY;
344
456
 
345
457
  return reinterpret_cast<PyObject*>(cnxn);
346
458
  }
@@ -351,25 +463,50 @@ static char set_attr_doc[] =
351
463
  "attr_id\n"
352
464
  " The attribute id (integer) to set. These are ODBC or driver constants.\n\n"
353
465
  "value\n"
354
- " An integer value.\n\n"
355
- "At this time, only integer values are supported and are always passed as SQLUINTEGER.";
466
+ " An integer or string value.";
356
467
 
357
468
  static PyObject* Connection_set_attr(PyObject* self, PyObject* args)
358
469
  {
359
470
  int id;
360
- int value;
361
- if (!PyArg_ParseTuple(args, "ii", &id, &value))
471
+ PyObject* value;
472
+ if (!PyArg_ParseTuple(args, "iO", &id, &value))
362
473
  return 0;
363
474
 
364
- Connection* cnxn = (Connection*)self;
475
+ Connection* cnxn = Connection_Validate(self);
476
+ if (!cnxn)
477
+ return 0;
365
478
 
366
479
  SQLRETURN ret;
367
- Py_BEGIN_ALLOW_THREADS
368
- ret = SQLSetConnectAttr(cnxn->hdbc, id, (SQLPOINTER)(intptr_t)value, SQL_IS_INTEGER);
369
- Py_END_ALLOW_THREADS
480
+ SQLWChar sqlchar; // declared here so buffer stays alive across the call
481
+
482
+ if (PyLong_Check(value))
483
+ {
484
+ long ival = PyLong_AsLong(value);
485
+ if (ival == -1 && PyErr_Occurred())
486
+ return 0;
487
+ Py_BEGIN_ALLOW_THREADS
488
+ ret = SQLSetConnectAttrW(cnxn->hdbc, id, (SQLPOINTER)(intptr_t)ival, SQL_IS_INTEGER);
489
+ Py_END_ALLOW_THREADS
490
+ }
491
+ else if (PyUnicode_Check(value))
492
+ {
493
+ sqlchar.set(value, "utf-16le");
494
+ if (!sqlchar.isValid())
495
+ return 0;
496
+ Py_BEGIN_ALLOW_THREADS
497
+ ret = SQLSetConnectAttrW(cnxn->hdbc, id, sqlchar.get(), SQL_NTS);
498
+ Py_END_ALLOW_THREADS
499
+ }
500
+ else
501
+ {
502
+ PyErr_Format(PyExc_TypeError, "set_attr value must be a string or integer, not '%s'",
503
+ Py_TYPE(value)->tp_name);
504
+ return 0;
505
+ }
370
506
 
371
507
  if (!SQL_SUCCEEDED(ret))
372
508
  return RaiseErrorFromHandle(cnxn, "SQLSetConnectAttr", cnxn->hdbc, SQL_NULL_HANDLE);
509
+
373
510
  Py_RETURN_NONE;
374
511
  }
375
512
 
@@ -695,7 +832,7 @@ static PyObject* Connection_getinfo(PyObject* self, PyObject* args)
695
832
  }
696
833
 
697
834
  if (i == _countof(aInfoTypes))
698
- return RaiseErrorV(0, ProgrammingError, "Unsupported getinfo value: %d", infotype);
835
+ return RaiseErrorV(0, ProgrammingError, "Unsupported getinfo value: %lu", infotype);
699
836
 
700
837
  char szBuffer[0x1000];
701
838
  SQLSMALLINT cch = 0;
@@ -720,7 +857,8 @@ static PyObject* Connection_getinfo(PyObject* self, PyObject* args)
720
857
  break;
721
858
 
722
859
  case GI_STRING:
723
- result = PyUnicode_FromStringAndSize(szBuffer, (Py_ssize_t)cch);
860
+ // On truncation cch is the full length, not what fit in the buffer.
861
+ result = PyUnicode_FromStringAndSize(szBuffer, min((Py_ssize_t)cch, (Py_ssize_t)sizeof(szBuffer) - 1));
724
862
  break;
725
863
 
726
864
  case GI_UINTEGER:
@@ -875,12 +1013,29 @@ static PyObject* Connection_getclosed(PyObject* self, void* closure)
875
1013
  Py_RETURN_FALSE;
876
1014
  }
877
1015
 
1016
+ static PyObject* Connection_gethdbc(PyObject* self, void* closure)
1017
+ {
1018
+ UNUSED(closure);
1019
+ Connection* cnxn;
1020
+
1021
+ if (!self || !Connection_Check(self))
1022
+ {
1023
+ PyErr_SetString(PyExc_TypeError, "Connection object required");
1024
+ return nullptr;
1025
+ }
1026
+
1027
+ cnxn = (Connection*)self;
1028
+
1029
+ return MakeVoidPointerFromHandle(cnxn->hdbc);
1030
+ }
878
1031
 
879
1032
  static PyObject* Connection_getsearchescape(PyObject* self, void* closure)
880
1033
  {
881
1034
  UNUSED(closure);
882
1035
 
883
- Connection* cnxn = (Connection*)self;
1036
+ Connection* cnxn = Connection_Validate(self);
1037
+ if (!cnxn)
1038
+ return 0;
884
1039
 
885
1040
  if (!cnxn->searchescape)
886
1041
  {
@@ -894,7 +1049,9 @@ static PyObject* Connection_getsearchescape(PyObject* self, void* closure)
894
1049
  if (!SQL_SUCCEEDED(ret))
895
1050
  return RaiseErrorFromHandle(cnxn, "SQLGetInfo", cnxn->hdbc, SQL_NULL_HANDLE);
896
1051
 
897
- cnxn->searchescape = PyUnicode_FromStringAndSize(sz, (Py_ssize_t)cch);
1052
+ cnxn->searchescape = PyUnicode_FromStringAndSize(sz, min((Py_ssize_t)cch, (Py_ssize_t)sizeof(sz) - 1));
1053
+ if (!cnxn->searchescape)
1054
+ return 0;
898
1055
  }
899
1056
 
900
1057
  Py_INCREF(cnxn->searchescape);
@@ -942,6 +1099,34 @@ static int Connection_setmaxwrite(PyObject* self, PyObject* value, void* closure
942
1099
  return 0;
943
1100
  }
944
1101
 
1102
+ static PyObject* Connection_getreadvarinitsize(PyObject* self, void* closure)
1103
+ {
1104
+ UNUSED(closure);
1105
+
1106
+ Connection* cnxn = Connection_Validate(self);
1107
+ if (!cnxn)
1108
+ return 0;
1109
+ return PyLong_FromSsize_t(cnxn->readvar_initsize);
1110
+ }
1111
+
1112
+ static int Connection_setreadvarinitsize(PyObject* self, PyObject* value, void* closure)
1113
+ {
1114
+ UNUSED(closure);
1115
+
1116
+ Connection* cnxn = Connection_Validate(self);
1117
+ if (!cnxn)
1118
+ return -1;
1119
+ Py_ssize_t v = PyLong_AsSsize_t(value);
1120
+ if (v == -1 && PyErr_Occurred())
1121
+ return -1;
1122
+ if (v < 0)
1123
+ {
1124
+ PyErr_SetString(PyExc_TypeError, "Cannot set readvar_initsize to a negative value.");
1125
+ return -1;
1126
+ }
1127
+ cnxn->readvar_initsize = v;
1128
+ return 0;
1129
+ }
945
1130
 
946
1131
  static PyObject* Connection_gettimeout(PyObject* self, void* closure)
947
1132
  {
@@ -991,6 +1176,124 @@ static int Connection_settimeout(PyObject* self, PyObject* value, void* closure)
991
1176
  return 0;
992
1177
  }
993
1178
 
1179
+ static const char* const DECIMAL_MODE_NAMES[] = { "binary", "text", "locale" };
1180
+
1181
+ static PyObject* Connection_getdecimalmode(PyObject* self, void* closure)
1182
+ {
1183
+ UNUSED(closure);
1184
+
1185
+ Connection* cnxn = Connection_Validate(self);
1186
+ if (!cnxn)
1187
+ return 0;
1188
+
1189
+ return PyUnicode_FromString(DECIMAL_MODE_NAMES[cnxn->decimal_mode]);
1190
+ }
1191
+
1192
+ static int SetDecimalModeFromBool(Connection* cnxn, PyObject* value, const char* attr)
1193
+ {
1194
+ // The bool values of fetch_decimal_as_string, kept until 6.0. True keeps its old meaning,
1195
+ // the locale path, rather than becoming "text". Since the getter returns True for both
1196
+ // text modes, True leaves 'text' alone, so saving and restoring the value changes nothing.
1197
+
1198
+ int isTrue = PyObject_IsTrue(value);
1199
+ if (isTrue < 0)
1200
+ return -1;
1201
+ int mode = !isTrue ? DECIMAL_MODE_BINARY
1202
+ : cnxn->decimal_mode == DECIMAL_MODE_TEXT ? DECIMAL_MODE_TEXT : DECIMAL_MODE_LOCALE;
1203
+ if (PyErr_WarnFormat(PyExc_FutureWarning, 1,
1204
+ "Setting %s to %s is deprecated and will not be supported in pyodbc 6.0; "
1205
+ "set decimal_mode = '%s' instead", attr, isTrue ? "True" : "False",
1206
+ DECIMAL_MODE_NAMES[mode]) < 0)
1207
+ return -1;
1208
+ cnxn->decimal_mode = mode;
1209
+ return 0;
1210
+ }
1211
+
1212
+ static int Connection_setdecimalmode(PyObject* self, PyObject* value, void* closure)
1213
+ {
1214
+ UNUSED(closure);
1215
+
1216
+ Connection* cnxn = Connection_Validate(self);
1217
+ if (!cnxn)
1218
+ return -1;
1219
+
1220
+ if (value == 0)
1221
+ {
1222
+ PyErr_SetString(PyExc_TypeError, "Cannot delete the decimal_mode attribute.");
1223
+ return -1;
1224
+ }
1225
+
1226
+ if (PyBool_Check(value))
1227
+ return SetDecimalModeFromBool(cnxn, value, "decimal_mode");
1228
+
1229
+ if (PyUnicode_Check(value))
1230
+ {
1231
+ for (int i = 0; i < (int)_countof(DECIMAL_MODE_NAMES); i++)
1232
+ {
1233
+ if (PyUnicode_CompareWithASCIIString(value, DECIMAL_MODE_NAMES[i]) == 0)
1234
+ {
1235
+ cnxn->decimal_mode = i;
1236
+ return 0;
1237
+ }
1238
+ }
1239
+ PyErr_Format(PyExc_ValueError,
1240
+ "decimal_mode must be 'binary', 'text', or 'locale', not %R", value);
1241
+ return -1;
1242
+ }
1243
+
1244
+ PyErr_Format(PyExc_TypeError, "decimal_mode must be a str, not %s", Py_TYPE(value)->tp_name);
1245
+ return -1;
1246
+ }
1247
+
1248
+ static PyObject* Connection_getfetchdecimalasstring(PyObject* self, void* closure)
1249
+ {
1250
+ UNUSED(closure);
1251
+
1252
+ Connection* cnxn = Connection_Validate(self);
1253
+ if (!cnxn)
1254
+ return 0;
1255
+
1256
+ if (PyErr_WarnEx(PyExc_FutureWarning,
1257
+ "fetch_decimal_as_string is deprecated and will be removed in pyodbc 6.0; "
1258
+ "use decimal_mode instead", 1) < 0)
1259
+ return 0;
1260
+
1261
+ return PyBool_FromLong(cnxn->decimal_mode != DECIMAL_MODE_BINARY);
1262
+ }
1263
+
1264
+ static int Connection_setfetchdecimalasstring(PyObject* self, PyObject* value, void* closure)
1265
+ {
1266
+ UNUSED(closure);
1267
+
1268
+ Connection* cnxn = Connection_Validate(self);
1269
+ if (!cnxn)
1270
+ return -1;
1271
+
1272
+ if (value == 0)
1273
+ {
1274
+ PyErr_SetString(PyExc_TypeError, "Cannot delete the fetch_decimal_as_string attribute.");
1275
+ return -1;
1276
+ }
1277
+
1278
+ return SetDecimalModeFromBool(cnxn, value, "fetch_decimal_as_string");
1279
+ }
1280
+
1281
+ static PyObject* Connection_getcompat_diagrec_byte_length(PyObject* self, void* closure)
1282
+ {
1283
+ return PyBool_FromLong(((Connection*)self)->compat_diagrec_byte_length);
1284
+ }
1285
+
1286
+ static int Connection_setcompat_diagrec_byte_length(PyObject* self, PyObject* value, void* closure)
1287
+ {
1288
+ if (!PyBool_Check(value))
1289
+ {
1290
+ PyErr_SetString(PyExc_TypeError, "compat_diagrec_byte_length must be a bool");
1291
+ return -1;
1292
+ }
1293
+ ((Connection*)self)->compat_diagrec_byte_length = (value == Py_True);
1294
+ return 0;
1295
+ }
1296
+
994
1297
  static bool _remove_converter(PyObject* self, SQLSMALLINT sqltype)
995
1298
  {
996
1299
  Connection* cnxn = (Connection*)self;
@@ -1272,7 +1575,6 @@ static PyObject* Connection_setencoding(PyObject* self, PyObject* args, PyObject
1272
1575
  {
1273
1576
  Connection* cnxn = (Connection*)self;
1274
1577
 
1275
- // In Python 3 we only support encodings for Unicode text.
1276
1578
  char* encoding = 0;
1277
1579
  int ctype = 0;
1278
1580
  static char *kwlist[] = { "encoding", "ctype", 0 };
@@ -1386,6 +1688,7 @@ static struct PyMethodDef Connection_methods[] =
1386
1688
  static PyGetSetDef Connection_getseters[] = {
1387
1689
  { "closed", (getter)Connection_getclosed, 0,
1388
1690
  "Returns True if the connection is closed; False otherwise.", 0},
1691
+ { "hdbc", (getter)Connection_gethdbc, 0, "ODBC connection handle.", 0 },
1389
1692
  { "searchescape", (getter)Connection_getsearchescape, 0,
1390
1693
  "The ODBC search pattern escape character, as returned by\n"
1391
1694
  "SQLGetInfo(SQL_SEARCH_PATTERN_ESCAPE). These are driver specific.", 0 },
@@ -1394,6 +1697,24 @@ static PyGetSetDef Connection_getseters[] = {
1394
1697
  { "timeout", Connection_gettimeout, Connection_settimeout,
1395
1698
  "The timeout in seconds, zero means no timeout.", 0 },
1396
1699
  { "maxwrite", Connection_getmaxwrite, Connection_setmaxwrite, "The maximum bytes to write before using SQLPutData.", 0 },
1700
+ { "readvar_initsize", Connection_getreadvarinitsize, Connection_setreadvarinitsize,
1701
+ "The initial buffer size in bytes for reading values from variable-length columns.", 0 },
1702
+ { "decimal_mode", Connection_getdecimalmode, Connection_setdecimalmode,
1703
+ "How DECIMAL and NUMERIC values are read:\n\n"
1704
+ "'binary': into a SQL_NUMERIC_STRUCT, which is not affected by the locale. This is the\n"
1705
+ " default except for PostgreSQL. The struct cannot hold NaN or Infinity, or more than\n"
1706
+ " 38 digits.\n"
1707
+ "'text': as text with no grouping separators: a sign, digits, and at most one decimal\n"
1708
+ " point, which can be '.' or ','; or NaN, Infinity, or -Infinity. Other text raises\n"
1709
+ " DataError. This is the default for PostgreSQL.\n"
1710
+ "'locale': as text, after removing everything but digits, '-', and the separator from\n"
1711
+ " setDecimalSeparator, which then becomes the decimal point. For drivers that add\n"
1712
+ " grouping separators or currency symbols.", 0 },
1713
+ { "fetch_decimal_as_string", Connection_getfetchdecimalasstring, Connection_setfetchdecimalasstring,
1714
+ "Deprecated; use decimal_mode. True means decimal_mode is not 'binary'. Setting True\n"
1715
+ "selects 'locale' and False selects 'binary'.", 0 },
1716
+ { "compat_diagrec_byte_length", Connection_getcompat_diagrec_byte_length, Connection_setcompat_diagrec_byte_length,
1717
+ "If True, the driver reports byte length instead of character length in SQLGetDiagRecW().", 0 },
1397
1718
  { 0 }
1398
1719
  };
1399
1720