forked from pymssql/pymssql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpymssql.pyx
699 lines (578 loc) · 20.8 KB
/
pymssql.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
"""DB-SIG compliant module for communicating with MS SQL servers"""
# pymssql.pyx
#
# Copyright (C) 2003 Joon-cheol Park <[email protected]>
# 2008 Andrzej Kukula <[email protected]>
# 2009 Damien Churchill <[email protected]>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301 USA
import datetime
import time
import _mssql
cimport _mssql
from cpython cimport bool, PY_MAJOR_VERSION
cdef extern from "pymssql_version.h":
const char *PYMSSQL_VERSION
__author__ = 'Damien Churchill <[email protected]>'
__full_version__ = PYMSSQL_VERSION.decode('ascii')
__version__ = '.'.join(__full_version__.split('.')[:3]) # drop '.dev' from 'X.Y.Z.dev'
# Strives for compliance with DB-API 2.0 (PEP 249)
# http://www.python.org/dev/peps/pep-0249/
apilevel = '2.0'
# module may be shared, but not connections
threadsafety = 1
# this module uses extended python format codes
paramstyle = 'pyformat'
from _mssql import set_wait_callback
# store a tuple of programming error codes
cdef object prog_errors = (
102, # syntax error
207, # invalid column name
208, # invalid object name
2812, # unknown procedure
4104 # multi-part identifier could not be bound
)
# store a tuple of integrity error codes
cdef object integrity_errors = (
515, # NULL insert
547, # FK related
2601, # violate unique index
2627, # violate UNIQUE KEY constraint
)
class DBAPIType:
def __init__(self, value):
self.value = value
def __cmp__(self, other):
if other == self.value:
return 0
if other < self.value:
return 1
else:
return -1
def __eq__(self, other):
return (other == self.value)
def __repr__(self):
return '<DBAPIType %s>' % self.value
STRING = DBAPIType(_mssql.STRING)
BINARY = DBAPIType(_mssql.BINARY)
NUMBER = DBAPIType(_mssql.NUMBER)
DATETIME = DBAPIType(_mssql.DATETIME)
DECIMAL = DBAPIType(_mssql.DECIMAL)
Date = datetime.date
Time = datetime.time
Timestamp = datetime.datetime
DateFromTicks = lambda ticks: Date(*time.localtime(ticks)[:3])
TimeFromTicks = lambda ticks: Time(*time.localtime(ticks)[3:6])
TimestampFromTicks = lambda ticks: Timestamp(*time.localtime(ticks)[:6])
Binary = bytes
cdef dict DBTYPES = {
'bool': _mssql.SQLBITN,
'str': _mssql.SQLVARCHAR,
'unicode': _mssql.SQLVARCHAR,
'Decimal': _mssql.SQLDECIMAL,
'datetime': _mssql.SQLDATETIME,
'date': _mssql.SQLDATETIME,
#Dump type for work vith None
'NoneType': _mssql.SQLVARCHAR,
}
cdef int py2db_type(py_type, value):
if PY_MAJOR_VERSION == 3:
if py_type == 'int':
if value is not None and value >= -2147483648 and value <= 2147483647: # -2^31 - 2^31-1
return _mssql.SQLINTN
else:
return _mssql.SQLINT8
else:
if py_type == 'int':
return _mssql.SQLINTN
if py_type == 'long':
return _mssql.SQLINT8
if py_type == 'float':
if value != 0 and not (-3.40E38 <= value <= -1.18E-38 or 1.18E-38 <= value <= 3.40E38):
return _mssql.SQLFLT8
else:
return _mssql.SQLFLT4
return DBTYPES[py_type]
try:
StandardError
except NameError:
StandardError = Exception
# exception hierarchy
class Warning(StandardError):
pass
class Error(StandardError):
pass
class InterfaceError(Error):
pass
class DatabaseError(Error):
pass
class DataError(Error):
pass
class OperationalError(DatabaseError):
pass
class IntegrityError(DatabaseError):
pass
class InternalError(DatabaseError):
pass
class ProgrammingError(DatabaseError):
pass
class NotSupportedError(DatabaseError):
pass
class ColumnsWithoutNamesError(InterfaceError):
def __init__(self, columns_without_names):
self.columns_without_names = columns_without_names
def __str__(self):
return 'Specified as_dict=True and ' \
'there are columns with no names: %r' \
% (self.columns_without_names,)
def row2dict(row):
"""Filter dict so it only has string keys; used when as_dict == True"""
return dict([(k, v) for k, v in row.items() if hasattr(k, 'startswith')])
# stored procedure output parameter
cdef class output:
cdef object _type
cdef object _value
property type:
"""
This is the type of the parameter.
"""
def __get__(self):
return self._type
property value:
"""
This is the value of the parameter.
"""
def __get__(self):
return self._value
def __init__(self, param_type, value=None):
self._type = param_type
self._value = value
######################
## Connection class ##
######################
cdef class Connection:
"""
This class represents an MS-SQL database connection.
"""
cdef bool _as_dict
cdef bool _autocommit
cdef _mssql.MSSQLConnection conn
property as_dict:
"""
Instructs all cursors this connection creates to return results
as a dictionary rather than a tuple.
"""
def __get__(self):
return self._as_dict
def __set__(self, value):
self._as_dict = value
property autocommit_state:
"""
The current state of autocommit on the connection.
"""
def __get__(self):
return self._autocommit
property _conn:
"""
INTERNAL PROPERTY. Returns the _mssql.MSSQLConnection object, and
raise exception if it's set to None. It's easier than adding the
necessary checks to every other method.
"""
def __get__(self):
if self.conn == None:
raise InterfaceError('Connection is closed.')
return self.conn
def __init__(self, conn, as_dict, autocommit):
self.conn = conn
self._autocommit = autocommit
self.as_dict = as_dict
if not autocommit:
try:
self._conn.execute_non_query('BEGIN TRAN')
except Exception, e:
raise OperationalError('Cannot start transaction: ' + str(e.args[0]))
def __dealloc__(self):
if self.conn:
self.close()
def autocommit(self, status):
"""
Turn autocommit ON or OFF.
"""
if status == self._autocommit:
return
tran_type = 'ROLLBACK' if status else 'BEGIN'
self._conn.execute_non_query('%s TRAN' % tran_type)
self._autocommit = status
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def close(self):
"""
Close the connection to the database. Implicitly rolls back all
uncommitted transactions.
"""
if self.conn:
self.conn.close()
self.conn = None
def commit(self):
"""
Commit transaction which is currently in progress.
"""
if self._autocommit == True:
return
try:
self._conn.execute_non_query('COMMIT TRAN')
self._conn.execute_non_query('BEGIN TRAN')
except Exception, e:
raise OperationalError('Cannot commit transaction: ' + str(e.args[0]))
def cursor(self, as_dict=None):
"""
Return cursor object that can be used to make queries and fetch
results from the database.
"""
if as_dict is None:
as_dict = self.as_dict
return Cursor(self, as_dict)
def rollback(self):
"""
Roll back transaction which is currently in progress.
"""
if self._autocommit == True:
return
try:
self._conn.execute_non_query('ROLLBACK TRAN')
except _mssql.MSSQLException, e:
# PEP 249 indicates that we have contract with the user that we will
# always have a transaction in place if autocommit is False.
# Therefore, it seems logical to ignore this exception since it
# indicates a situation we shouldn't ever encounter anyway. However,
# it can happen when an error is severe enough to cause a
# "batch-abort". In that case, SQL Server *implicitly* rolls back
# the transaction for us (how helpful!). But there doesn't seem
# to be any way for us to know if an error is severe enough to cause
# a batch abort:
# http://stackoverflow.com/questions/5877162/why-does-microsoft-sql-server-implicitly-rollback-when-a-create-statement-fails
#
# the alternative is to do 'select @@trancount' before each rollback
# but that is slower and doesn't seem to offer any benefit.
if 'The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION' not in str(e):
raise
try:
self._conn.execute_non_query('BEGIN TRAN')
except Exception, e:
raise OperationalError('Cannot begin transaction: ' + str(e.args[0]))
##################
## Cursor class ##
##################
cdef class Cursor:
"""
This class represents a database cursor, which is used to issue queries
and fetch results from a database connection.
"""
cdef Connection conn
cdef public tuple description
cdef int batchsize
cdef int _batchsize
cdef int _rownumber
cdef bool as_dict
cdef object _returnvalue
property connection:
def __get__(self):
return self.conn
property lastrowid:
def __get__(self):
return self.conn.conn.identity
property rowcount:
def __get__(self):
return self._rownumber
property returnvalue:
def __get__(self):
return self._returnvalue
property rownumber:
def __get__(self):
return self._rownumber
property _source:
def __get__(self):
if self.conn == None:
raise InterfaceError('Cursor is closed.')
return self.conn
def __init__(self, conn, as_dict):
self.conn = conn
self.description = None
self._batchsize = 1
self._rownumber = 0
self._returnvalue = None
self.as_dict = as_dict
def __iter__(self):
"""
Return self to make cursors compatibile with Python iteration
protocol.
"""
return self
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def callproc(self, str procname, parameters=()):
"""
Call a stored procedure with the given name.
:param procname: The name of the procedure to call
:type procname: str
:keyword parameters: The optional parameters for the procedure
:type parameters: sequence
"""
self._returnvalue = None
proc = self._source._conn.init_procedure(procname)
for parameter in parameters:
if type(parameter) is output:
param_type = parameter.type
param_value = parameter.value
param_output = True
else:
param_type = type(parameter)
param_value = parameter
param_output = False
try:
type_name = param_type.__name__
db_type = py2db_type(type_name, param_value)
except (AttributeError, KeyError):
raise NotSupportedError('Unable to determine database type from python %s type' % type_name)
proc.bind(param_value, db_type, output=param_output)
try:
self._returnvalue = proc.execute()
except _mssql.MSSQLDatabaseException, e:
raise DatabaseError, e.args[0]
return tuple([proc.parameters[p] for p in proc.parameters])
def close(self):
"""
Closes the cursor. The cursor is unusable from this point.
"""
self.conn = None
self.description = None
def execute(self, operation, params=()):
self.description = None
self._rownumber = 0
try:
if not params:
self._source._conn.execute_query(operation)
else:
self._source._conn.execute_query(operation, params)
self.description = self._source._conn.get_header()
self._rownumber = self._source._conn.rows_affected
if self.as_dict and self.description:
columns_without_names = [
idx
for idx, column_descriptor in enumerate(self.description)
if len(column_descriptor[0]) == 0
]
if columns_without_names:
raise ColumnsWithoutNamesError(columns_without_names)
except _mssql.MSSQLDatabaseException, e:
if e.number in prog_errors:
raise ProgrammingError, e.args[0]
if e.number in integrity_errors:
raise IntegrityError, e.args[0]
raise OperationalError, e.args[0]
except _mssql.MSSQLDriverException, e:
raise InterfaceError, e.args[0]
def executemany(self, operation, params_seq):
self.description = None
rownumber = 0
for params in params_seq:
self.execute(operation, params)
# support correct rowcount across multiple executes
rownumber += self._rownumber
self._rownumber = rownumber
def nextset(self):
try:
if not self._source._conn.nextresult():
return None
self._rownumber = 0
self.description = self._source._conn.get_header()
return 1
except _mssql.MSSQLDatabaseException, e:
raise OperationalError, e.args[0]
except _mssql.MSSQLDriverException, e:
raise InterfaceError, e.args[0]
cdef getrow(self):
"""
Helper method used by fetchone and fetchmany to fetch and handle
converting the row if as_dict = True.
"""
row_format = _mssql.ROW_FORMAT_DICT if self.as_dict else _mssql.ROW_FORMAT_TUPLE
row = next(self._source._conn.get_iterator(row_format))
if not self.as_dict:
return row
return row2dict(row)
def fetchone(self):
if self.description is None:
raise OperationalError('Statement not executed or executed statement has no resultset')
try:
return self.getrow()
except StopIteration:
return None
except _mssql.MSSQLDatabaseException, e:
raise OperationalError, e.args[0]
except _mssql.MSSQLDriverException, e:
raise InterfaceError, e.args[0]
def fetchmany(self, size=None):
if self.description is None:
raise OperationalError('Statement not executed or executed statement has no resultset')
if size == None:
size = self._batchsize
self.batchsize = size
try:
rows = []
for i in xrange(size):
try:
rows.append(self.getrow())
except StopIteration:
break
return rows
except _mssql.MSSQLDatabaseException, e:
raise OperationalError, e.args[0]
except _mssql.MSSQLDriverException, e:
raise InterfaceError, e.args[0]
def fetchall(self):
if self.description is None:
raise OperationalError('Statement not executed or executed statement has no resultset')
try:
rows = []
while True:
try:
rows.append(self.getrow())
except StopIteration:
break
self._rownumber = self._source._conn.rows_affected
return rows
except _mssql.MSSQLDatabaseException, e:
raise OperationalError, e.args[0]
except _mssql.MSSQLDriverException, e:
raise InterfaceError, e.args[0]
def __next__(self):
try:
row = self.getrow()
self._rownumber += 1
return row
except _mssql.MSSQLDatabaseException, e:
raise OperationalError, e.args[0]
except _mssql.MSSQLDriverException, e:
raise InterfaceError, e.args[0]
def setinputsizes(self, sizes=None):
"""
This method does nothing, as permitted by DB-API specification.
"""
pass
def setoutputsize(self, size=None, column=0):
"""
This method does nothing, as permitted by DB-API specification.
"""
pass
def connect(server='.', user='', password='', database='', timeout=0,
login_timeout=60, charset='UTF-8', as_dict=False,
host='', appname=None, port='1433', conn_properties=None, autocommit=False):
"""
Constructor for creating a connection to the database. Returns a
Connection object.
:param server: database host
:type server: string
:param user: database user to connect as
:type user: string
:param password: user's password
:type password: string
:param database: the database to initially connect to
:type database: string
:param timeout: query timeout in seconds, default 0 (no timeout)
:type timeout: int
:param login_timeout: timeout for connection and login in seconds, default 60
:type login_timeout: int
:param charset: character set with which to connect to the database
:type charset: string
:keyword as_dict: whether rows should be returned as dictionaries instead of tuples.
:type as_dict: boolean
:keyword appname: Set the application name to use for the connection
:type appname: string
:keyword port: the TCP port to use to connect to the server
:type port: string
:keyword conn_properties: SQL queries to send to the server upon connection
establishment. Can be a string or another kind
of iterable of strings
:keyword autocommit whether to use default autocommiting mode or not
:type autocommit: boolean
"""
# set the login timeout
try:
login_timeout = int(login_timeout)
except ValueError:
login_timeout = 0
_mssql.login_timeout = login_timeout
# default query timeout
try:
timeout = int(timeout)
except ValueError:
timeout = 0
if host:
server = host
try:
conn = _mssql.connect(server=server, user=user, password=password,
charset=charset, database=database,
appname=appname, port=port,
conn_properties=conn_properties)
except _mssql.MSSQLDatabaseException, e:
raise OperationalError(e.args[0])
except _mssql.MSSQLDriverException, e:
raise InterfaceError(e.args[0])
if timeout != 0:
conn.query_timeout = timeout
return Connection(conn, as_dict, autocommit)
def get_max_connections():
"""
Get the maximum number of simulatenous connections pymssql will open
to the server.
"""
return _mssql.get_max_connections()
def set_max_connections(int limit):
"""
Set maximum simultaneous connections db-lib will open to the server.
:param limit: the connection limit
:type limit: int
"""
_mssql.set_max_connections(limit)
cdef extern from "sybdb.h":
char *dbversion()
# Only recent versions of FreeTDS have the ct_config function
# so this can break builds
# Maybe later we can enable this or make it conditional
DEF HAS_CT_CONFIG = False
IF HAS_CT_CONFIG:
cdef extern from "ctpublic.h":
ctypedef int CS_INT
ctypedef void CS_VOID
struct _CS_CONTEXT
ctypedef _CS_CONTEXT CS_CONTEXT
ctypedef CS_INT CS_RETCODE
int CS_GET, CS_VERSION
CS_RETCODE ct_config(CS_CONTEXT * ctx, CS_INT action, CS_INT property,
CS_VOID * buffer, CS_INT buflen, CS_INT * outlen)
def get_freetds_version():
cdef CS_CONTEXT *ctx = NULL
cdef char buf[256]
cdef int outlen
ret = ct_config(ctx, CS_GET, CS_VERSION, buf, 256, &outlen)
return buf
def get_dbversion():
return dbversion()