forked from pymssql/pymssql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_mssql.pyx
1890 lines (1529 loc) · 63.7 KB
/
_mssql.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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
This is an effort to convert the pymssql low-level C module to Cython.
"""
#
# _mssql.pyx
#
# Copyright (C) 2003 Joon-cheol Park <[email protected]>
# 2008 Andrzej Kukula <[email protected]>
# 2009-2010 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
#
DEF PYMSSQL_DEBUG = 0
DEF PYMSSQL_DEBUG_ERRORS = 0
DEF PYMSSQL_CHARSETBUFSIZE = 100
DEF MSSQLDB_MSGSIZE = 1024
DEF PYMSSQL_MSGSIZE = (MSSQLDB_MSGSIZE * 8)
DEF EXCOMM = 9
# Provide constants missing in FreeTDS 0.82 so that we can build against it
DEF DBVERSION_71 = 5
DEF DBVERSION_72 = 6
ROW_FORMAT_TUPLE = 1
ROW_FORMAT_DICT = 2
cdef int _ROW_FORMAT_TUPLE = ROW_FORMAT_TUPLE
cdef int _ROW_FORMAT_DICT = ROW_FORMAT_DICT
from cpython cimport PY_MAJOR_VERSION, PY_MINOR_VERSION
import os
import sys
import socket
import decimal
import binascii
import datetime
import re
import uuid
from sqlfront cimport *
from libc.stdio cimport fprintf, snprintf, stderr, FILE
from libc.string cimport strlen, strncpy, memcpy
from cpython cimport bool
from cpython.mem cimport PyMem_Malloc, PyMem_Free
from cpython.long cimport PY_LONG_LONG
from cpython.ref cimport Py_INCREF
from cpython.tuple cimport PyTuple_New, PyTuple_SetItem
cdef extern from "pymssql_version.h":
const char *PYMSSQL_VERSION
# Vars to store messages from the server in
cdef int _mssql_last_msg_no = 0
cdef int _mssql_last_msg_severity = 0
cdef int _mssql_last_msg_state = 0
cdef int _mssql_last_msg_line = 0
cdef char *_mssql_last_msg_str = <char *>PyMem_Malloc(PYMSSQL_MSGSIZE)
_mssql_last_msg_str[0] = <char>0
cdef char *_mssql_last_msg_srv = <char *>PyMem_Malloc(PYMSSQL_MSGSIZE)
_mssql_last_msg_srv[0] = <char>0
cdef char *_mssql_last_msg_proc = <char *>PyMem_Malloc(PYMSSQL_MSGSIZE)
_mssql_last_msg_proc[0] = <char>0
IF PYMSSQL_DEBUG == 1:
cdef int _row_count = 0
cdef bytes HOSTNAME = socket.gethostname().encode('utf-8')
# List to store the connection objects in
cdef list connection_object_list = list()
# Store the 32bit max int
cdef int MAX_INT = 2147483647
# Store the module version
__version__ = PYMSSQL_VERSION.decode('ascii')
#############################
## DB-API type definitions ##
#############################
STRING = 1
BINARY = 2
NUMBER = 3
DATETIME = 4
DECIMAL = 5
##################
## DB-LIB types ##
##################
SQLBINARY = SYBBINARY
SQLBIT = SYBBIT
SQLBITN = 104
SQLCHAR = SYBCHAR
SQLDATETIME = SYBDATETIME
SQLDATETIM4 = SYBDATETIME4
SQLDATETIMN = SYBDATETIMN
SQLDECIMAL = SYBDECIMAL
SQLFLT4 = SYBREAL
SQLFLT8 = SYBFLT8
SQLFLTN = SYBFLTN
SQLIMAGE = SYBIMAGE
SQLINT1 = SYBINT1
SQLINT2 = SYBINT2
SQLINT4 = SYBINT4
SQLINT8 = SYBINT8
SQLINTN = SYBINTN
SQLMONEY = SYBMONEY
SQLMONEY4 = SYBMONEY4
SQLMONEYN = SYBMONEYN
SQLNUMERIC = SYBNUMERIC
SQLREAL = SYBREAL
SQLTEXT = SYBTEXT
SQLVARBINARY = SYBVARBINARY
SQLVARCHAR = SYBVARCHAR
SQLUUID = 36
#######################
## Exception classes ##
#######################
cdef extern from "pyerrors.h":
ctypedef class __builtin__.Exception [object PyBaseExceptionObject]:
pass
cdef class MSSQLException(Exception):
"""
Base exception class for the MSSQL driver.
"""
cdef class MSSQLDriverException(MSSQLException):
"""
Inherits from the base class and raised when an error is caused within
the driver itself.
"""
cdef class MSSQLDatabaseException(MSSQLException):
"""
Raised when an error occurs within the database.
"""
cdef readonly int number
cdef readonly int severity
cdef readonly int state
cdef readonly int line
cdef readonly char *text
cdef readonly char *srvname
cdef readonly char *procname
property message:
def __get__(self):
if self.procname:
return 'SQL Server message %d, severity %d, state %d, ' \
'procedure %s, line %d:\n%s' % (self.number,
self.severity, self.state, self.procname,
self.line, self.text)
else:
return 'SQL Server message %d, severity %d, state %d, ' \
'line %d:\n%s' % (self.number, self.severity,
self.state, self.line, self.text)
# Module attributes for configuring _mssql
login_timeout = 60
min_error_severity = 6
wait_callback = None
def set_wait_callback(a_callable):
global wait_callback
wait_callback = a_callable
# Buffer size for large numbers
DEF NUMERIC_BUF_SZ = 45
cdef bytes ensure_bytes(s, encoding='utf-8'):
try:
decoded = s.decode(encoding)
return decoded.encode(encoding)
except AttributeError:
return s.encode(encoding)
cdef void log(char * message, ...):
if PYMSSQL_DEBUG == 1:
fprintf(stderr, "+++ %s\n", message)
###################
## Error Handler ##
###################
cdef int err_handler(DBPROCESS *dbproc, int severity, int dberr, int oserr,
char *dberrstr, char *oserrstr) with gil:
cdef char *mssql_lastmsgstr
cdef int *mssql_lastmsgno
cdef int *mssql_lastmsgseverity
cdef int *mssql_lastmsgstate
cdef int _min_error_severity = min_error_severity
cdef char mssql_message[PYMSSQL_MSGSIZE]
if severity < _min_error_severity:
return INT_CANCEL
if dberrstr == NULL:
dberrstr = ''
if oserrstr == NULL:
oserrstr = ''
IF PYMSSQL_DEBUG == 1 or PYMSSQL_DEBUG_ERRORS == 1:
fprintf(stderr, "\n*** err_handler(dbproc = %p, severity = %d, " \
"dberr = %d, oserr = %d, dberrstr = '%s', oserrstr = '%s'); " \
"DBDEAD(dbproc) = %d\n", <void *>dbproc, severity, dberr,
oserr, dberrstr, oserrstr, DBDEAD(dbproc));
fprintf(stderr, "*** previous max severity = %d\n\n",
_mssql_last_msg_severity);
mssql_lastmsgstr = _mssql_last_msg_str
mssql_lastmsgno = &_mssql_last_msg_no
mssql_lastmsgseverity = &_mssql_last_msg_severity
mssql_lastmsgstate = &_mssql_last_msg_state
for conn in connection_object_list:
if dbproc != (<MSSQLConnection>conn).dbproc:
continue
mssql_lastmsgstr = (<MSSQLConnection>conn).last_msg_str
mssql_lastmsgno = &(<MSSQLConnection>conn).last_msg_no
mssql_lastmsgseverity = &(<MSSQLConnection>conn).last_msg_severity
mssql_lastmsgstate = &(<MSSQLConnection>conn).last_msg_state
break
if severity > mssql_lastmsgseverity[0]:
mssql_lastmsgseverity[0] = severity
mssql_lastmsgno[0] = dberr
mssql_lastmsgstate[0] = oserr
if oserr != DBNOERR and oserr != 0:
if severity == EXCOMM:
snprintf(
mssql_message, sizeof(mssql_message),
'%sDB-Lib error message %d, severity %d:\n%s\nNet-Lib error during %s (%d)\n',
mssql_lastmsgstr, dberr, severity, dberrstr, oserrstr, oserr)
else:
snprintf(
mssql_message, sizeof(mssql_message),
'%sDB-Lib error message %d, severity %d:\n%s\nOperating System error during %s (%d)\n',
mssql_lastmsgstr, dberr, severity, dberrstr, oserrstr, oserr)
else:
snprintf(
mssql_message, sizeof(mssql_message),
'%sDB-Lib error message %d, severity %d:\n%s\n',
mssql_lastmsgstr, dberr, severity, dberrstr)
strncpy(mssql_lastmsgstr, mssql_message, PYMSSQL_MSGSIZE)
mssql_lastmsgstr[ PYMSSQL_MSGSIZE - 1 ] = '\0'
return INT_CANCEL
#####################
## Message Handler ##
#####################
cdef int msg_handler(DBPROCESS *dbproc, DBINT msgno, int msgstate,
int severity, char *msgtext, char *srvname, char *procname,
LINE_T line) with gil:
cdef int *mssql_lastmsgno
cdef int *mssql_lastmsgseverity
cdef int *mssql_lastmsgstate
cdef int *mssql_lastmsgline
cdef char *mssql_lastmsgstr
cdef char *mssql_lastmsgsrv
cdef char *mssql_lastmsgproc
cdef int _min_error_severity = min_error_severity
IF PYMSSQL_DEBUG == 1:
fprintf(stderr, "\n+++ msg_handler(dbproc = %p, msgno = %d, " \
"msgstate = %d, severity = %d, msgtext = '%s', " \
"srvname = '%s', procname = '%s', line = %d)\n",
<void *>dbproc, msgno, msgstate, severity, msgtext, srvname,
procname, line);
fprintf(stderr, "+++ previous max severity = %d\n\n",
_mssql_last_msg_severity);
if severity < _min_error_severity:
return INT_CANCEL
mssql_lastmsgstr = _mssql_last_msg_str
mssql_lastmsgsrv = _mssql_last_msg_srv
mssql_lastmsgproc = _mssql_last_msg_proc
mssql_lastmsgno = &_mssql_last_msg_no
mssql_lastmsgseverity = &_mssql_last_msg_severity
mssql_lastmsgstate = &_mssql_last_msg_state
mssql_lastmsgline = &_mssql_last_msg_line
for conn in connection_object_list:
if dbproc != (<MSSQLConnection>conn).dbproc:
continue
mssql_lastmsgstr = (<MSSQLConnection>conn).last_msg_str
mssql_lastmsgsrv = (<MSSQLConnection>conn).last_msg_srv
mssql_lastmsgproc = (<MSSQLConnection>conn).last_msg_proc
mssql_lastmsgno = &(<MSSQLConnection>conn).last_msg_no
mssql_lastmsgseverity = &(<MSSQLConnection>conn).last_msg_severity
mssql_lastmsgstate = &(<MSSQLConnection>conn).last_msg_state
mssql_lastmsgline = &(<MSSQLConnection>conn).last_msg_line
break
# Calculate the maximum severity of all messages in a row
# Fill the remaining fields as this is going to raise the exception
if severity > mssql_lastmsgseverity[0]:
mssql_lastmsgseverity[0] = severity
mssql_lastmsgno[0] = msgno
mssql_lastmsgstate[0] = msgstate
mssql_lastmsgline[0] = line
strncpy(mssql_lastmsgstr, msgtext, PYMSSQL_MSGSIZE)
strncpy(mssql_lastmsgsrv, srvname, PYMSSQL_MSGSIZE)
strncpy(mssql_lastmsgproc, procname, PYMSSQL_MSGSIZE)
return 0
cdef int db_sqlexec(DBPROCESS *dbproc):
cdef RETCODE rtc
# The dbsqlsend function sends Transact-SQL statements, stored in the
# command buffer of the DBPROCESS, to SQL Server.
#
# It does not wait for a response. This gives us an opportunity to do other
# things while waiting for the server response.
#
# After dbsqlsend returns SUCCEED, dbsqlok must be called to verify the
# accuracy of the command batch. Then dbresults can be called to process
# the results.
with nogil:
rtc = dbsqlsend(dbproc)
if rtc != SUCCEED:
return rtc
# If we've reached here, dbsqlsend didn't fail so the query is in progress.
# Wait for results to come back and return the return code, optionally
# calling wait_callback first...
return db_sqlok(dbproc)
cdef int db_sqlok(DBPROCESS *dbproc):
cdef RETCODE rtc
# If there is a wait callback, call it with the file descriptor we're
# waiting on.
# The wait_callback is a good place to do things like yield to another
# gevent greenlet -- e.g.: gevent.socket.wait_read(read_fileno)
if wait_callback:
read_fileno = dbiordesc(dbproc)
wait_callback(read_fileno)
# dbsqlok following dbsqlsend is the equivalent of dbsqlexec. This function
# must be called after dbsqlsend returns SUCCEED. When dbsqlok returns,
# then dbresults can be called to process the results.
with nogil:
rtc = dbsqlok(dbproc)
return rtc
cdef void clr_err(MSSQLConnection conn):
if conn != None:
conn.last_msg_no = 0
conn.last_msg_severity = 0
conn.last_msg_state = 0
conn.last_msg_str[0] = 0
else:
_mssql_last_msg_no = 0
_mssql_last_msg_severity = 0
_mssql_last_msg_state = 0
_mssql_last_msg_str[0] = 0
cdef RETCODE db_cancel(MSSQLConnection conn):
cdef RETCODE rtc
if conn == None:
return SUCCEED
if conn.dbproc == NULL:
return SUCCEED
with nogil:
rtc = dbcancel(conn.dbproc);
conn.clear_metadata()
return rtc
##############################
## MSSQL Row Iterator Class ##
##############################
cdef class MSSQLRowIterator:
def __init__(self, connection, int row_format):
self.conn = connection
self.row_format = row_format
def __iter__(self):
return self
def __next__(self):
assert_connected(self.conn)
clr_err(self.conn)
return self.conn.fetch_next_row(1, self.row_format)
############################
## MSSQL Connection Class ##
############################
cdef class MSSQLConnection:
property charset:
"""
The current encoding in use.
"""
def __get__(self):
if strlen(self._charset):
return self._charset.decode('ascii') if PY_MAJOR_VERSION == 3 else self._charset
return None
property connected:
"""
True if the connection to a database is open.
"""
def __get__(self):
return self._connected
property identity:
"""
Returns identity value of the last inserted row. If the previous
operation did not involve inserting a row into a table with an
identity column, None is returned.
** Usage **
>>> conn.execute_non_query("INSERT INTO table (name) VALUES ('John')")
>>> print 'Last inserted row has ID = %s' % conn.identity
Last inserted row has ID = 178
"""
def __get__(self):
return self.execute_scalar('SELECT SCOPE_IDENTITY()')
property query_timeout:
"""
A
"""
def __get__(self):
return self._query_timeout
def __set__(self, value):
cdef int val = int(value)
cdef RETCODE rtc
if val < 0:
raise ValueError("The 'query_timeout' attribute must be >= 0.")
# currently this will set it application wide :-(
rtc = dbsettime(val)
check_and_raise(rtc, self)
# if all is fine then set our attribute
self._query_timeout = val
property rows_affected:
"""
Number of rows affected by last query. For SELECT statements this
value is only meaningful after reading all rows.
"""
def __get__(self):
return self._rows_affected
property tds_version:
"""
Returns what TDS version the connection is using.
"""
def __get__(self):
cdef int version = dbtds(self.dbproc)
if version == 9:
return 8.0
elif version == 8:
return 7.0
elif version == 4:
return 4.2
def __cinit__(self):
log("_mssql.MSSQLConnection.__cinit__()")
self._connected = 0
self._charset = <char *>PyMem_Malloc(PYMSSQL_CHARSETBUFSIZE)
self._charset[0] = <char>0
self.last_msg_str = <char *>PyMem_Malloc(PYMSSQL_MSGSIZE)
self.last_msg_str[0] = <char>0
self.last_msg_srv = <char *>PyMem_Malloc(PYMSSQL_MSGSIZE)
self.last_msg_srv[0] = <char>0
self.last_msg_proc = <char *>PyMem_Malloc(PYMSSQL_MSGSIZE)
self.last_msg_proc[0] = <char>0
self.column_names = None
self.column_types = None
def __init__(self, server="localhost", user="sa", password="",
charset='UTF-8', database='', appname=None, port='1433', tds_version='7.1'):
log("_mssql.MSSQLConnection.__init__()")
cdef LOGINREC *login
cdef RETCODE rtc
cdef char *_charset
# support MS methods of connecting locally
instance = ""
if "\\" in server:
server, instance = server.split("\\")
if server in (".", "(local)"):
server = "localhost"
server = server + "\\" + instance if instance else server
login = dblogin()
if login == NULL:
raise MSSQLDriverException("dblogin() failed")
appname = appname or "pymssql"
# For Python 3, we need to convert unicode to byte strings
cdef bytes user_bytes = user.encode('utf-8')
cdef char *user_cstr = user_bytes
cdef bytes password_bytes = password.encode('utf-8')
cdef char *password_cstr = password_bytes
cdef bytes appname_bytes = appname.encode('utf-8')
cdef char *appname_cstr = appname_bytes
DBSETLUSER(login, user_cstr)
DBSETLPWD(login, password_cstr)
DBSETLAPP(login, appname_cstr)
DBSETLVERSION(login, _tds_ver_str_to_constant(tds_version))
# add the port to the server string if it doesn't have one already and
# if we are not using an instance
if ':' not in server and not instance:
server = '%s:%s' % (server, port)
# override the HOST to be the portion without the server, otherwise
# FreeTDS chokes when server still has the port definition.
# BUT, a patch on the mailing list fixes the need for this. I am
# leaving it here just to remind us how to fix the problem if the bug
# doesn't get fixed for a while. But if it does get fixed, this code
# can be deleted.
# patch: http://lists.ibiblio.org/pipermail/freetds/2011q2/026997.html
#if ':' in server:
# os.environ['TDSHOST'] = server.split(':', 1)[0]
#else:
# os.environ['TDSHOST'] = server
# Add ourselves to the global connection list
connection_object_list.append(self)
cdef bytes charset_bytes
# Set the character set name
if charset:
charset_bytes = charset.encode('utf-8')
_charset = charset_bytes
strncpy(self._charset, _charset, PYMSSQL_CHARSETBUFSIZE)
DBSETLCHARSET(login, self._charset)
# Set the login timeout
dbsetlogintime(login_timeout)
cdef bytes server_bytes = server.encode('utf-8')
cdef char *server_cstr = server_bytes
# Connect to the server
with nogil:
self.dbproc = dbopen(login, server_cstr)
# Frees the login record, can be called immediately after dbopen.
dbloginfree(login)
if self.dbproc == NULL:
log("_mssql.MSSQLConnection.__init__() -> dbopen() returned NULL")
connection_object_list.remove(self)
maybe_raise_MSSQLDatabaseException(None)
raise MSSQLDriverException("Connection to the database failed for an unknown reason.")
self._connected = 1
log("_mssql.MSSQLConnection.__init__() -> dbcmd() setting connection values")
# Set some connection properties to some reasonable values
dbcmd(self.dbproc,
"SET ARITHABORT ON;" \
"SET CONCAT_NULL_YIELDS_NULL ON;" \
"SET ANSI_NULLS ON;" \
"SET ANSI_NULL_DFLT_ON ON;" \
"SET ANSI_PADDING ON;" \
"SET ANSI_WARNINGS ON;" \
"SET ANSI_NULL_DFLT_ON ON;" \
"SET CURSOR_CLOSE_ON_COMMIT ON;" \
"SET QUOTED_IDENTIFIER ON;" \
# http://msdn.microsoft.com/en-us/library/aa259190%28v=sql.80%29.aspx
"SET TEXTSIZE 2147483647;"
)
rtc = db_sqlexec(self.dbproc)
if (rtc == FAIL):
raise MSSQLDriverException("Could not set connection properties")
db_cancel(self)
clr_err(self)
if database:
self.select_db(database)
def __dealloc__(self):
log("_mssql.MSSQLConnection.__dealloc__()")
self.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def __iter__(self):
assert_connected(self)
clr_err(self)
return MSSQLRowIterator(self, ROW_FORMAT_DICT)
cpdef cancel(self):
"""
cancel() -- cancel all pending results.
This function cancels all pending results from the last SQL operation.
It can be called more than once in a row. No exception is raised in
this case.
"""
log("_mssql.MSSQLConnection.cancel()")
cdef RETCODE rtc
assert_connected(self)
clr_err(self)
rtc = db_cancel(self)
check_and_raise(rtc, self)
cdef void clear_metadata(self):
log("_mssql.MSSQLConnection.clear_metadata()")
self.column_names = None
self.column_types = None
self.num_columns = 0
self.last_dbresults = 0
def close(self):
"""
close() -- close connection to an MS SQL Server.
This function tries to close the connection and free all memory used.
It can be called more than once in a row. No exception is raised in
this case.
"""
log("_mssql.MSSQLConnection.close()")
if self == None:
return None
if not self._connected:
return None
clr_err(self)
with nogil:
dbclose(self.dbproc)
self.dbproc = NULL
self._connected = 0
PyMem_Free(self.last_msg_proc)
PyMem_Free(self.last_msg_srv)
PyMem_Free(self.last_msg_str)
PyMem_Free(self._charset)
connection_object_list.remove(self)
cdef object convert_db_value(self, BYTE *data, int dbtype, int length):
log("_mssql.MSSQLConnection.convert_db_value()")
cdef char buf[NUMERIC_BUF_SZ] # buffer in which we store text rep of bug nums
cdef int converted_length
cdef long prevPrecision
cdef BYTE precision
cdef DBDATEREC di
cdef DBDATETIME dt
cdef DBCOL dbcol
IF PYMSSQL_DEBUG == 1:
sys.stderr.write("convert_db_value: dbtype = %d; length = %d\n" % (dbtype, length))
if dbtype == SQLBIT:
return bool(<int>(<DBBIT *>data)[0])
elif dbtype == SQLINT1:
return int(<int>(<DBTINYINT *>data)[0])
elif dbtype == SQLINT2:
return int(<int>(<DBSMALLINT *>data)[0])
elif dbtype == SQLINT4:
return int(<int>(<DBINT *>data)[0])
elif dbtype == SQLINT8:
return long(<PY_LONG_LONG>(<PY_LONG_LONG *>data)[0])
elif dbtype == SQLFLT4:
return float(<float>(<DBREAL *>data)[0])
elif dbtype == SQLFLT8:
return float(<double>(<DBFLT8 *>data)[0])
elif dbtype in (SQLMONEY, SQLMONEY4, SQLNUMERIC, SQLDECIMAL):
dbcol.SizeOfStruct = sizeof(dbcol)
if dbtype in (SQLMONEY, SQLMONEY4):
precision = 4
else:
precision = 0
converted_length = dbconvert(self.dbproc, dbtype, data, -1, SQLCHAR,
<BYTE *>buf, NUMERIC_BUF_SZ)
with decimal.localcontext() as ctx:
# Python 3 doesn't like decimal.localcontext() with prec == 0
ctx.prec = precision if precision > 0 else 1
return decimal.Decimal(_remove_locale(buf, converted_length).decode(self._charset))
elif dbtype == SQLDATETIM4:
dbconvert(self.dbproc, dbtype, data, -1, SQLDATETIME,
<BYTE *>&dt, -1)
dbdatecrack(self.dbproc, &di, <DBDATETIME *><BYTE *>&dt)
return datetime.datetime(di.year, di.month, di.day,
di.hour, di.minute, di.second, di.millisecond * 1000)
elif dbtype == SQLDATETIME:
dbdatecrack(self.dbproc, &di, <DBDATETIME *>data)
return datetime.datetime(di.year, di.month, di.day,
di.hour, di.minute, di.second, di.millisecond * 1000)
elif dbtype in (SQLVARCHAR, SQLCHAR, SQLTEXT):
if strlen(self._charset):
return (<char *>data)[:length].decode(self._charset)
else:
return (<char *>data)[:length]
elif dbtype == SQLUUID:
return uuid.UUID(bytes_le=(<char *>data)[:length])
else:
return (<char *>data)[:length]
cdef int convert_python_value(self, object value, BYTE **dbValue,
int *dbtype, int *length) except 1:
log("_mssql.MSSQLConnection.convert_python_value()")
cdef int *intValue
cdef double *dblValue
cdef PY_LONG_LONG *longValue
cdef char *strValue
cdef char *tmp
cdef BYTE *binValue
cdef DBTYPEINFO decimal_type_info
IF PYMSSQL_DEBUG == 1:
sys.stderr.write("convert_python_value: value = %r; dbtype = %d" % (value, dbtype[0]))
if value is None:
dbValue[0] = <BYTE *>NULL
return 0
if dbtype[0] in (SQLBIT, SQLBITN):
intValue = <int *>PyMem_Malloc(sizeof(int))
intValue[0] = <int>value
dbValue[0] = <BYTE *><DBBIT *>intValue
return 0
if dbtype[0] == SQLINTN:
dbtype[0] = SQLINT4
if dbtype[0] in (SQLINT1, SQLINT2, SQLINT4):
if value > MAX_INT:
raise MSSQLDriverException('value cannot be larger than %d' % MAX_INT)
intValue = <int *>PyMem_Malloc(sizeof(int))
intValue[0] = <int>value
if dbtype[0] == SQLINT1:
dbValue[0] = <BYTE *><DBTINYINT *>intValue
return 0
if dbtype[0] == SQLINT2:
dbValue[0] = <BYTE *><DBSMALLINT *>intValue
return 0
if dbtype[0] == SQLINT4:
dbValue[0] = <BYTE *><DBINT *>intValue
return 0
if dbtype[0] == SQLINT8:
longValue = <PY_LONG_LONG *>PyMem_Malloc(sizeof(PY_LONG_LONG))
longValue[0] = <PY_LONG_LONG>value
dbValue[0] = <BYTE *>longValue
return 0
if dbtype[0] in (SQLFLT4, SQLFLT8):
dblValue = <double *>PyMem_Malloc(sizeof(double))
dblValue[0] = <double>value
if dbtype[0] == SQLFLT4:
dbValue[0] = <BYTE *><DBREAL *>dblValue
return 0
if dbtype[0] == SQLFLT8:
dbValue[0] = <BYTE *><DBFLT8 *>dblValue
return 0
if dbtype[0] in (SQLDATETIM4, SQLDATETIME):
if type(value) not in (datetime.date, datetime.datetime):
raise TypeError('value can only be a date or datetime')
value = value.strftime('%Y-%m-%d %H:%M:%S.') + \
"%03d" % (value.microsecond // 1000)
value = value.encode(self.charset)
dbtype[0] = SQLCHAR
if dbtype[0] in (SQLNUMERIC, SQLDECIMAL):
# There seems to be no harm in setting precision higher than
# necessary
decimal_type_info.precision = 33
# Figure out `scale` - number of digits after decimal point
decimal_type_info.scale = abs(value.as_tuple().exponent)
# Need this to prevent Cython error:
# "Obtaining 'BYTE *' from temporary Python value"
# bytes_value = bytes(str(value), encoding="ascii")
bytes_value = unicode(value).encode("ascii")
decValue = <DBDECIMAL *>PyMem_Malloc(sizeof(DBDECIMAL))
length[0] = dbconvert_ps(
self.dbproc,
SQLCHAR,
bytes_value,
-1,
dbtype[0],
<BYTE *>decValue,
sizeof(DBDECIMAL),
&decimal_type_info,
)
dbValue[0] = <BYTE *>decValue
IF PYMSSQL_DEBUG == 1:
fprintf(stderr, "convert_python_value: Converted value to DBDECIMAL with length = %d\n", length[0])
for i in range(0, 35):
fprintf(stderr, "convert_python_value: dbValue[0][%d] = %d\n", i, dbValue[0][i])
return 0
if dbtype[0] in (SQLMONEY, SQLMONEY4, SQLNUMERIC, SQLDECIMAL):
if type(value) in (int, long, bytes):
value = decimal.Decimal(value)
if type(value) not in (decimal.Decimal, float):
raise TypeError('value can only be a Decimal')
value = str(value)
dbtype[0] = SQLCHAR
if dbtype[0] in (SQLVARCHAR, SQLCHAR, SQLTEXT):
if not hasattr(value, 'startswith'):
raise TypeError('value must be a string type')
if strlen(self._charset) > 0 and type(value) is unicode:
value = value.encode(self.charset)
strValue = <char *>PyMem_Malloc(len(value) + 1)
tmp = value
strncpy(strValue, tmp, len(value) + 1)
strValue[ len(value) ] = '\0';
dbValue[0] = <BYTE *>strValue
return 0
if dbtype[0] in (SQLBINARY, SQLVARBINARY, SQLIMAGE):
if type(value) is not str:
raise TypeError('value can only be str')
binValue = <BYTE *>PyMem_Malloc(len(value))
memcpy(binValue, <char *>value, len(value))
length[0] = len(value)
dbValue[0] = <BYTE *>binValue
return 0
if dbtype[0] == SQLUUID:
binValue = <BYTE *>PyMem_Malloc(16)
memcpy(binValue, <char *>value.bytes_le, 16)
length[0] = 16
dbValue[0] = <BYTE *>binValue
return 0
# No conversion was possible so raise an error
raise MSSQLDriverException('Unable to convert value')
cpdef execute_non_query(self, query_string, params=None):
"""
execute_non_query(query_string, params=None)
This method sends a query to the MS SQL Server to which this object
instance is connected. After completion, its results (if any) are
discarded. An exception is raised on failure. If there are any pending
results or rows prior to executing this command, they are silently
discarded. This method accepts Python formatting. Please see
execute_query() for more details.
This method is useful for INSERT, UPDATE, DELETE and for Data
Definition Language commands, i.e. when you need to alter your database
schema.
After calling this method, rows_affected property contains number of
rows affected by the last SQL command.
"""
log("_mssql.MSSQLConnection.execute_non_query() BEGIN")
cdef RETCODE rtc
self.format_and_run_query(query_string, params)
with nogil:
dbresults(self.dbproc)
self._rows_affected = dbcount(self.dbproc)
rtc = db_cancel(self)
check_and_raise(rtc, self)
log("_mssql.MSSQLConnection.execute_non_query() END")
cpdef execute_query(self, query_string, params=None):
"""
execute_query(query_string, params=None)
This method sends a query to the MS SQL Server to which this object
instance is connected. An exception is raised on failure. If there
are pending results or rows prior to executing this command, they
are silently discarded. After calling this method you may iterate
over the connection object to get rows returned by the query.
You can use Python formatting here and all values get properly
quoted:
conn.execute_query('SELECT * FROM empl WHERE id=%d', 13)
conn.execute_query('SELECT * FROM empl WHERE id IN (%s)', ((5,6),))
conn.execute_query('SELECT * FROM empl WHERE name=%s', 'John Doe')
conn.execute_query('SELECT * FROM empl WHERE name LIKE %s', 'J%')
conn.execute_query('SELECT * FROM empl WHERE name=%(name)s AND \
city=%(city)s', { 'name': 'John Doe', 'city': 'Nowhere' } )
conn.execute_query('SELECT * FROM cust WHERE salesrep=%s \
AND id IN (%s)', ('John Doe', (1,2,3)))
conn.execute_query('SELECT * FROM empl WHERE id IN (%s)',\
(tuple(xrange(4)),))
conn.execute_query('SELECT * FROM empl WHERE id IN (%s)',\
(tuple([3,5,7,11]),))
This method is intented to be used on queries that return results,
i.e. SELECT. After calling this method AND reading all rows from,
result rows_affected property contains number of rows returned by
last command (this is how MS SQL returns it).
"""
log("_mssql.MSSQLConnection.execute_query() BEGIN")
self.format_and_run_query(query_string, params)
self.get_result()
log("_mssql.MSSQLConnection.execute_query() END")
cpdef execute_row(self, query_string, params=None):
"""
execute_row(query_string, params=None)
This method sends a query to the MS SQL Server to which this object
instance is connected, then returns first row of data from result.
An exception is raised on failure. If there are pending results or
rows prior to executing this command, they are silently discarded.
This method accepts Python formatting. Please see execute_query()
for details.
This method is useful if you want just a single row and don't want
or don't need to iterate, as in:
conn.execute_row('SELECT * FROM employees WHERE id=%d', 13)
This method works exactly the same as 'iter(conn).next()'. Remaining
rows, if any, can still be iterated after calling this method.
"""
log("_mssql.MSSQLConnection.execute_row()")
self.format_and_run_query(query_string, params)