-
Notifications
You must be signed in to change notification settings - Fork 1
/
_mssql.pyx
1516 lines (1204 loc) · 48.9 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_CHARSETBUFSIZE = 100
DEF MSSQLDB_MSGSIZE = 1024
DEF PYMSSQL_MSGSIZE = (MSSQLDB_MSGSIZE * 8)
DEF EXCOMM = 9
from cpython cimport PY_MAJOR_VERSION, PY_MINOR_VERSION
if PY_MAJOR_VERSION >= 2 and PY_MINOR_VERSION >= 5:
import uuid
import socket
import decimal
import datetime
from sqlfront cimport *
from libc.stdio cimport fprintf, sprintf, stderr, FILE
from libc.string cimport strlen, strcpy, strncpy, memcpy
from cpython cimport bool
from cpython.mem cimport PyMem_Malloc, PyMem_Free
from cpython.long cimport PY_LONG_LONG
# 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)
cdef char *_mssql_last_msg_srv = <char *>PyMem_Malloc(PYMSSQL_MSGSIZE)
cdef char *_mssql_last_msg_proc = <char *>PyMem_Malloc(PYMSSQL_MSGSIZE)
IF PYMSSQL_DEBUG == 1:
cdef int _row_count = 0
cdef object _decimal_context
cdef bytes HOSTNAME = socket.gethostname()
# 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__ = '1.9.909'
#############################
## 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
# Buffer size for large numbers
DEF NUMERIC_BUF_SZ = 45
cdef void log(char * message, ...):
if PYMSSQL_DEBUG != 1:
return
fprintf(stderr, "+++ %s\n", message)
###################
## Error Handler ##
###################
cdef int err_handler(DBPROCESS *dbproc, int severity, int dberr, int oserr,
char *dberrstr, char *oserrstr):
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]
cdef char error_type[16]
if severity < _min_error_severity:
return INT_CANCEL
IF PYMSSQL_DEBUG == 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
sprintf(mssql_message, '%sDB-Lib error message %d, severity %d:\n%s\n',
mssql_lastmsgstr, dberr, severity, dberrstr)
if oserr != DBNOERR and oserr != 0:
error_type[0] = 'Net-Lib' if severity == EXCOMM else 'Operating System'
sprintf(mssql_message, '%s%s error during %s', error_type, oserrstr)
#strncpy(mssql_lastmsgstr, mssql_message, PYMSSQL_MSGSIZE)
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):
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
with nogil:
rtc = dbsqlexec(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
else:
_mssql_last_msg_no = 0
_mssql_last_msg_severity = 0
_mssql_last_msg_state = 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):
self.conn = connection
def __iter__(self):
return self
def __next__(self):
assert_connected(self.conn)
clr_err(self.conn)
return self.conn.fetch_next_row_dict(1)
############################
## MSSQL Connection Class ##
############################
cdef class MSSQLConnection:
property charset:
"""
The current encoding in use.
"""
def __get__(self):
if strlen(self._charset):
return 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='', database='', appname=None):
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("Out of memory")
appname = appname or "pymssql"
DBSETLUSER(login, user)
DBSETLPWD(login, password)
DBSETLAPP(login, appname)
DBSETLHOST(login, HOSTNAME);
# Add ourselves to the global connection list
connection_object_list.append(self)
# Set the character set name
if charset:
_charset = charset
strncpy(self._charset, _charset, PYMSSQL_CHARSETBUFSIZE)
DBSETLCHARSET(login, self._charset)
# Set the login timeout
dbsetlogintime(login_timeout)
# Connect to the server
self.dbproc = dbopen(login, server)
# Frees the login record, can be called immediately after dbopen.
dbloginfree(login)
if self.dbproc == NULL:
connection_object_list.remove(self)
maybe_raise_MSSQLDatabaseException(None)
raise MSSQLDriverException("Connection to the database failed for an unknown reason.")
self._connected = 1
# 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;"
)
rtc = dbsqlexec(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 __iter__(self):
assert_connected(self)
clr_err(self)
return MSSQLRowIterator(self)
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_str)
PyMem_Free(self._charset)
connection_object_list.remove(self)
cdef object convert_db_value(self, BYTE *data, int type, 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 len
cdef long prevPrecision
cdef BYTE precision
cdef DBDATEREC di
cdef DBDATETIME dt
cdef DBCOL dbcol
if type == SQLBIT:
return bool(<int>(<DBBIT *>data)[0])
elif type == SQLINT1:
return int(<int>(<DBTINYINT *>data)[0])
elif type == SQLINT2:
return int(<int>(<DBSMALLINT *>data)[0])
elif type == SQLINT4:
return int(<int>(<DBINT *>data)[0])
elif type == SQLINT8:
return long(<PY_LONG_LONG>(<PY_LONG_LONG *>data)[0])
elif type == SQLFLT4:
return float(<float>(<DBREAL *>data)[0])
elif type == SQLFLT8:
return float(<float>(<DBFLT8 *>data)[0])
elif type in (SQLMONEY, SQLMONEY4, SQLNUMERIC, SQLDECIMAL):
dbcol.SizeOfStruct = sizeof(dbcol)
if type in (SQLMONEY, SQLMONEY4):
precision = 4
else:
precision = dbcol.Scale
prevPrecision = _decimal_context.prec
_decimal_context.prec = precision
len = dbconvert(self.dbproc, type, data, -1, SQLCHAR,
<BYTE *>buf, NUMERIC_BUF_SZ)
return decimal.Decimal(_remove_locale(buf, len))
elif type == SQLDATETIM4:
dbconvert(self.dbproc, type, 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 type == 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 type in (SQLVARCHAR, SQLCHAR, SQLTEXT):
if strlen(self._charset):
return (<char *>data)[:length].decode(self._charset)
else:
return (<char *>data)[:length]
elif type == SQLUUID and (PY_MAJOR_VERSION >= 2 and PY_MINOR_VERSION >= 5):
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, *tmp
cdef BYTE *binValue
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.') + \
str(value.microsecond / 1000)
dbtype[0] = SQLCHAR
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 type(value) not in (str, unicode):
raise TypeError('value can only be str or unicode')
if strlen(self._charset) > 0 and type(value) is unicode:
value = value.encode(self._charset)
strValue = <char *>PyMem_Malloc(len(value) + 1)
tmp = value
strcpy(strValue, tmp)
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
# 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()")
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)
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()")
self.format_and_run_query(query_string, params)
self.get_result()
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)
return self.fetch_next_row_dict(0)
cpdef execute_scalar(self, query_string, params=None):
"""
execute_scalar(query_string, params=None)
This method sends a query to the MS SQL Server to which this object
instance is connected, then returns first column of first row 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 value, as in:
conn.execute_scalar('SELECT COUNT(*) FROM employees')
This method works in the same way as 'iter(conn).next()[0]'.
Remaining rows, if any, can still be iterated after calling this
method.
"""
cdef RETCODE rtc
log("_mssql.MSSQLConnection.execute_scalar()")
self.format_and_run_query(query_string, params)
self.get_result()
with nogil:
rtc = dbnextrow(self.dbproc)
self._rows_affected = dbcount(self.dbproc)
if rtc == NO_MORE_ROWS:
self.clear_metadata()
self.last_dbresults = 0
return None
return self.get_row(rtc)[0]
cdef fetch_next_row(self, int throw):
cdef RETCODE rtc
log("_mssql.MSSQLConnection.fetch_next_row()")
self.get_result()
if self.last_dbresults == NO_MORE_RESULTS:
self.clear_metadata()
if throw:
raise StopIteration
return None
with nogil:
rtc = dbnextrow(self.dbproc)
check_cancel_and_raise(rtc, self)
if rtc == NO_MORE_ROWS:
self.clear_metadata()
# 'rows_affected' is nonzero only after all records are read
self._rows_affected = dbcount(self.dbproc)
if throw:
raise StopIteration
return None
return self.get_row(rtc)
cdef fetch_next_row_dict(self, int throw):
cdef int col
log("_mssql.MSSQLConnection.fetch_next_row_dict()")
row_dict = {}
row = self.fetch_next_row(throw)
for col in xrange(1, self.num_columns + 1):
name = self.column_names[col - 1]
value = row[col - 1]
# Add key by column name, only if the column has a name
if name:
row_dict[name] = value
row_dict[col - 1] = value
return row_dict
cdef format_and_run_query(self, query_string, params=None):
"""
This is a helper function, which does most of the work needed by any
execute_*() function. It returns NULL on error, None on success.
"""
cdef RETCODE rtc
log("_mssql.MSSQLConnection.format_and_run_query()")
# Cancel any pending results
self.cancel()
if params:
query_string = self.format_sql_command(query_string, params)
# Prepare the query buffer
dbcmd(self.dbproc, query_string)
# Execute the query
rtc = db_sqlexec(self.dbproc)
check_cancel_and_raise(rtc, self)
cdef format_sql_command(self, format, params=None):
log("_mssql.MSSQLConnection.format_sql_command()")
if params is None:
return format
if not issubclass(type(params),
(bool, int, long, float, unicode, str,
datetime.datetime, datetime.date, dict, tuple)):
raise ValueError("'params' arg can be only a tuple or a dictionary.")
if strlen(self._charset):
quoted = _quote_data(params, self._charset)
else:
quoted = _quote_data(params)
return format % quoted
def get_header(self):
"""
get_header() -- get the Python DB-API compliant header information.
This method is infrastructure and doesn't need to be called by your
code. It returns a list of 7-element tuples describing the current
result header. Only name and DB-API compliant type is filled, rest
of the data is None, as permitted by the specs.
"""
cdef int col
log("_mssql.MSSQLConnection.get_header()")
self.get_result()
if self.num_columns == 0:
return None
header_tuple = []
for col in xrange(1, self.num_columns + 1):
col_name = self.column_names[col - 1]
col_type = self.column_types[col - 1]
header_tuple.append((col_name, col_type, None, None, None, None, None))
return tuple(header_tuple)
cdef get_result(self):
cdef int coltype
log("_mssql.MSSQLConnection.get_result()")
if self.last_dbresults:
return None
self.clear_metadata()
# Since python doesn't have a do/while loop do it this way
while True:
with nogil:
self.last_dbresults = dbresults(self.dbproc)
self.num_columns = dbnumcols(self.dbproc)
if self.last_dbresults != SUCCEED or self.num_columns > 0:
break
check_cancel_and_raise(self.last_dbresults, self)
self._rows_affected = dbcount(self.dbproc)
if self.last_dbresults == NO_MORE_RESULTS:
self.num_columns = 0
return None
self.num_columns = dbnumcols(self.dbproc)
column_names = list()
column_types = list()
for col in xrange(1, self.num_columns + 1):
column_names.append(dbcolname(self.dbproc, col))
coltype = dbcoltype(self.dbproc, col)
column_types.append(get_api_coltype(coltype))