forked from jasongs/pymssql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpymssql.pyx
541 lines (445 loc) · 14.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
"""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
__author__ = 'Damien Churchill <[email protected]>'
__version__ = '2.0.0'
import _mssql
cimport _mssql
from cpython cimport bool
# comliant with DB SIG 2.0
apilevel = '2.0'
# module may be shared, but not connections
threadsafety = 1
# this module uses extended python format codes
paramstyle = 'pyformat'
# 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
)
cdef class DBAPIType:
cdef tuple values
def __init__(self, *values):
self.values = values
def __cmp__(self, other):
if other in self.values:
return 0
if other < self.values:
return 1
else:
return -1
STRING = DBAPIType(_mssql.STRING)
BINARY = DBAPIType(_mssql.BINARY)
NUMBER = DBAPIType(_mssql.NUMBER)
DATETIME = DBAPIType(_mssql.DATETIME)
DECIMAL = DBAPIType(_mssql.DECIMAL)
cdef dict DBTYPES = {
'bool': _mssql.SQLBITN,
'str': _mssql.SQLVARCHAR,
'int': _mssql.SQLINTN,
'long': _mssql.SQLINT8,
'Decimal': _mssql.SQLDECIMAL,
'datetime': _mssql.SQLDATETIME,
'date': _mssql.SQLDATETIME
}
# 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
# 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):
self.conn = conn
self._autocommit = False
self.as_dict = as_dict
try:
self._conn.execute_non_query('BEGIN TRAN')
except Exception, e:
raise OperationalError('Cannot start transation: ' + str(e[0]))
def __del__(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 close(self):
"""
Close the connection to the databsae. 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 transation: ' + str(e[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')
self._conn.execute_non_query('BEGIN TRAN')
except Exception, e:
raise OperationalError('Cannot roll back transation: ' + str(e[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 callproc(self, bytes 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 = DBTYPES[type_name]
except (AttributeError, KeyError):
raise NotSupportedError('Unable to determine database type')
proc.bind(param_value, db_type, output=param_output)
self._returnvalue = proc.execute()
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
except _mssql.MSSQLDatabaseException, e:
if e.number in prog_errors:
raise ProgrammingError, e[0]
raise OperationalError, e[0]
except _mssql.MSSQLDriverException, e:
raise InterfaceError, e[0]
def executemany(self, operation, params_seq):
self.description = None
for params in params_seq:
self.execute(operation, params)
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[0]
except _mssql.MSSQLDriverException, e:
raise InterfaceError, e[0]
return None
cdef getrow(self):
"""
Helper method used by fetchone and fetchmany to fetch and handle
converting the row if as_dict = False.
"""
row = iter(self._source._conn).next()
self._rownumber = self._source._conn.rows_affected
if self.as_dict:
return row
return tuple([row[r] for r in sorted(row) if type(r) == int])
def fetchone(self):
if self._source._conn.get_header() == None:
raise OperationalError('No data available')
try:
return self.getrow()
except StopIteration:
return None
except _mssql.MSSQLDatabaseException, e:
raise OperationalError, e[0]
except _mssql.MSSQLDriverException, e:
raise InterfaceError, e[0]
def fetchmany(self, size=None):
if self._source._conn.get_header() == None:
raise OperationalError('No data available')
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[0]
except _mssql.MSSQLDriverException, e:
raise InterfaceError, e[0]
def fetchall(self):
if self._source._conn.get_header() == None:
raise OperationalError('No data available')
try:
if self.as_dict:
rows = [row for row in self._source._conn]
else:
rows = [tuple([row[r] for r in sorted(row.keys()) if \
type(r) == int]) for row in self._source._conn]
self._rownumber = self._source._conn.rows_affected
return rows
except _mssql.MSSQLDatabaseException, e:
raise OperationalError, e[0]
except _mssql.MSSQLDriverException, e:
raise InterfaceError, e[0]
def __next__(self):
try:
row = self.getrow()
self._rownumber += 1
return row
except _mssql.MSSQLDatabaseException, e:
raise OperationalError, e[0]
except _mssql.MSSQLDriverException, e:
raise InterfaceError, e[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=None, as_dict=False,
host='', appname=None):
"""
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
"""
_mssql.login_timeout = login_timeout
# set the login timeout
try:
login_timeout = int(login_timeout)
except ValueError:
login_timeout = 0
# default query timeout
try:
timeout = int(timeout)
except ValueError:
timeout = 0
if host:
server = host
try:
conn = _mssql.connect(server, user, password, charset, database,
appname)
except _mssql.MSSQLDatabaseException, e:
raise OperationalError(e[0])
except _mssql.MSSQLDriverException, e:
raise InterfaceError(e[0])
if timeout != 0:
conn.query_timeout = timeout
return Connection(conn, as_dict)
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)