Repository navigation
Expand file tree
/
Copy pathThinkSQL.py
More file actions
executable file
·1484 lines (1165 loc) · 55.1 KB
/
Copy pathThinkSQL.py
File metadata and controls
executable file
·1484 lines (1165 loc) · 55.1 KB
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
'''A Pure Python DB-API 2.0 compliant interface to ThinkSQL.
Copyright © 2000-2012 Greg Gaughan
http://www.thinksql.co.uk
'''
from string import split,replace
import struct
import cStringIO
import warnings
import socket
import datetime
try:
from fixedpoint import FixedPoint
have_fixedpoint = True
except ImportError:
have_fixedpoint = False
apilevel='2.0'
threadsafety=1
paramstyle='qmark'
__copyright__ = "(c)Copyright 2000-2012 Greg Gaughan"
__author__ = "Greg Gaughan"
def connect(dsn=None, user=None, password=None, host=None,
database=None, port=None):
'''Create and open a connection.
connect(dsn=None, user='DEFAULT', password='', host='localhost',
database='', port=9075)
Returns a connection object.
'''
#Defaults
_d = {'host':'localhost','port':9075, 'database':'',
'user':'DEFAULT', 'password':''}
#todo Parse any DSN
#Now use any keywords
if (user is not None): _d['user'] = user
if (password is not None): _d['password'] = password
if (host is not None): _d['host'] = host
try:
params = split(host,':')
_d['host'] = params[0]
_d['port'] = params[1]
except:
pass
if (database is not None): _d['database']=database
if (port is not None):_d['port'] = port
return connection(_d['host'], _d['port'], _d['database'],
_d['user'], _d['password'])
#Connection class -------------------------------------------------------------
class connection:
def __init__(self, host=None, port=None, catalog=None,
user=None, password=None):
self.state=_stateClosed
self.marshalBuffer=marshalBuffer(host, port)
self._Server=''
self._Catalog=catalog
self._Username=user
self._Password=password
self._Autocommit=False #Python has it right, unlike ODBC, JDBC etc!
self.resultErrCode=None
self.resultErrText=''
if self.marshalBuffer.sendHandshake()!=_ok: #send raw handshake
raise HandshakeError, str(_seHandshakeFailed)+' '+_seHandshakeFailedText
#Now the server knows we're using CLI protocol we can use the marshal buffer
self.marshalBuffer.putSQLUSMALLINT(_clientCLIversion) #special version marker for initial protocol handshake
if _clientCLIversion>=93:
self.marshalBuffer.putSQLUSMALLINT(_CLI_PYTHON_DBAPI)
if self.marshalBuffer.send()!=_ok:
raise HandshakeError, str(_seHandshakeFailed)+' '+_seHandshakeFailedText
#Wait for handshake response
if self.marshalBuffer.read()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
functionId=self.marshalBuffer.getFunction()
if functionId!=_SQL_API_handshake:
raise HandshakeError, str(_seHandshakeFailed)+' '+_seHandshakeFailedText
self.serverCLIversion=self.marshalBuffer.getSQLUSMALLINT() #note server's protocol
if self.serverCLIversion>=93:
self.serverTransactionKey=self.marshalBuffer.getSQLPOINTER() #note server's transaction key
#Now SQLconnect
self.marshalBuffer.clearToSend()
self.marshalBuffer.putFunction(_SQL_API_SQLCONNECT)
self.marshalBuffer.putSQLHDBC(0) #(int)(self)
if self._Catalog=='':
self.marshalBuffer.putpUCHAR_SWORD(self._Server)
else:
self.marshalBuffer.putpUCHAR_SWORD(self._Server+'.'+self._Catalog)
self.marshalBuffer.putpUCHAR_SWORD(self._Username)
self.marshalBuffer.putpUCHAR_SWORD(self._Password) #todo encrypt
if self.marshalBuffer.send()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
#Wait for read to return the response
if self.marshalBuffer.read()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
functionId=self.marshalBuffer.getFunction()
if functionId!=_SQL_API_SQLCONNECT:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
self.resultCode=self.marshalBuffer.getRETCODE()
#if error, then get error details: local-number, default-text
self.errCount=self.marshalBuffer.getSQLINTEGER() #error count
if self.resultCode==_SQL_ERROR:
for err in range(self.errCount):
self.resultErrCode=self.marshalBuffer.getSQLINTEGER()
self.resultErrText=self.marshalBuffer.getpUCHAR_SWORD()
raise DatabaseError, str(self.resultErrCode)+' '+self.resultErrText
#Ok, we're connected
self.state=_stateOpen
def cursor(self):
'''Create a new cursor on the connection.
'''
if self.state!=_stateOpen:
raise InterfaceError, str(_seConnectionNotOpen)+' '+_seConnectionNotOpenText
return cursor(self)
def close(self):
'''Close the connection.
'''
#Negotiate disconnection
if self.state!=_stateOpen:
raise InterfaceError, str(_seConnectionNotOpen)+' '+_seConnectionNotOpenText
self.marshalBuffer.clearToSend()
self.marshalBuffer.putFunction(_SQL_API_SQLDISCONNECT)
self.marshalBuffer.putSQLHDBC(0) #(int)(self)
if self.marshalBuffer.send()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
#Wait for read to return the response
if self.marshalBuffer.read()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
functionId=self.marshalBuffer.getFunction()
if functionId!=_SQL_API_SQLDISCONNECT:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
self.resultCode=self.marshalBuffer.getRETCODE()
#if error, then get error details: local-number, default-text
self.errCount=self.marshalBuffer.getSQLINTEGER() #error count
if self.resultCode==_SQL_ERROR:
for err in range(self.errCount):
self.resultErrCode=self.marshalBuffer.getSQLINTEGER()
self.resultErrText=self.marshalBuffer.getpUCHAR_SWORD()
raise DatabaseError, str(self.resultErrCode)+' '+self.resultErrText
#Try to disconnect from the server
self.marshalBuffer.close() #close this connection
self.state=_stateClosed
def commit(self):
'''Commit the current transaction.
'''
#Send SQLendTran to server
self.marshalBuffer.clearToSend()
self.marshalBuffer.putFunction(_SQL_API_SQLENDTRAN)
self.marshalBuffer.putSQLHDBC(0) #todo pass TranId?
self.marshalBuffer.putSQLSMALLINT(_SQL_COMMIT)
if self.marshalBuffer.send()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
#Wait for read to return the response
if self.marshalBuffer.read()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
functionId=self.marshalBuffer.getFunction()
if functionId!=_SQL_API_SQLENDTRAN:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
self.resultCode=self.marshalBuffer.getRETCODE()
#if error, then get error details: local-number, default-text
self.errCount=self.marshalBuffer.getSQLINTEGER() #error count
if self.resultCode==_SQL_ERROR:
for err in range(self.errCount):
self.resultErrCode=self.marshalBuffer.getSQLINTEGER()
self.resultErrText=self.marshalBuffer.getpUCHAR_SWORD()
raise DatabaseError, str(self.resultErrCode)+' '+self.resultErrText
def rollback(self):
'''Rollback the current transaction.
'''
#Send SQLendTran to server
self.marshalBuffer.clearToSend()
self.marshalBuffer.putFunction(_SQL_API_SQLENDTRAN)
self.marshalBuffer.putSQLHDBC(0) #todo pass TranId?
self.marshalBuffer.putSQLSMALLINT(_SQL_ROLLBACK)
if self.marshalBuffer.send()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
#Wait for read to return the response
if self.marshalBuffer.read()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
functionId=self.marshalBuffer.getFunction()
if functionId!=_SQL_API_SQLENDTRAN:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
self.resultCode=self.marshalBuffer.getRETCODE()
#if error, then get error details: local-number, default-text
self.errCount=self.marshalBuffer.getSQLINTEGER() #error count
if self.resultCode==_SQL_ERROR:
for err in range(self.errCount):
self.resultErrCode=self.marshalBuffer.getSQLINTEGER()
self.resultErrText=self.marshalBuffer.getpUCHAR_SWORD()
raise DatabaseError, str(self.resultErrCode)+' '+self.resultErrText
def __del__(self):
if self.state==_stateOpen:
self.close()
#Cursor class -----------------------------------------------------------------
class cursor(object):
def __init__(self, conn):
'''Open a new cursor (statement) on the specified connection.
'''
self._Con=conn
self.colCount=None
self.col=[]
self.paramCount=None
self.param=[]
self.serverStatementHandle=-1 #=> not connected
self.resultSet=False
self.prepared=False
self._affectedRowCount=None
self.lastSQL=None
self.lastArraySize=1 #server default
self._description=None
self.resultErrCode=None
self.resultErrText=''
#We notify the server of this new command(=stmt)
self._Con.marshalBuffer.clearToSend()
self._Con.marshalBuffer.putFunction(_SQL_API_SQLALLOCHANDLE)
self._Con.marshalBuffer.putSQLSMALLINT(_SQL_HANDLE_STMT)
self._Con.marshalBuffer.putSQLHDBC(0) #todo _Con
if self._Con.marshalBuffer.send()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
#Wait for response
if self._Con.marshalBuffer.read()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
functionId=self._Con.marshalBuffer.getFunction()
if functionId!=_SQL_API_SQLALLOCHANDLE:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
serverS=self._Con.marshalBuffer.getSQLHSTMT() #server will return 0 if failed
self.resultCode=self._Con.marshalBuffer.getRETCODE()
#if error, then get error details: local-number, default-text
self.errCount=self._Con.marshalBuffer.getSQLINTEGER() #error count
if self.resultCode==_SQL_ERROR:
for err in range(self.errCount):
self.resultErrCode=self._Con.marshalBuffer.getSQLINTEGER()
self.resultErrText=self._Con.marshalBuffer.getpUCHAR_SWORD()
raise DatabaseError, str(self.resultErrCode)+' '+self.resultErrText
self.serverStatementHandle=serverS #we will pass this reference to server in future calls
def close(self):
'''Close the cursor.
'''
if self.serverStatementHandle<=0:
pass
else:
self._resultSetClose() #close the server cursor, if any
#Free the server handle
self._Con.marshalBuffer.clearToSend()
self._Con.marshalBuffer.putFunction(_SQL_API_SQLFREEHANDLE)
self._Con.marshalBuffer.putSQLSMALLINT(_SQL_HANDLE_STMT)
self._Con.marshalBuffer.putSQLHSTMT(self.serverStatementHandle) #pass server statement ref
if self._Con.marshalBuffer.send()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
#Wait for response
if self._Con.marshalBuffer.read()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
functionId=self._Con.marshalBuffer.getFunction()
if functionId!=_SQL_API_SQLFREEHANDLE:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
self.resultCode=self._Con.marshalBuffer.getRETCODE()
#if error, then get error details: local-number, default-text
self.errCount=self._Con.marshalBuffer.getSQLINTEGER() #error count
if self.resultCode==_SQL_ERROR:
for err in range(self.errCount):
self.resultErrCode=self._Con.marshalBuffer.getSQLINTEGER()
self.resultErrText=self._Con.marshalBuffer.getpUCHAR_SWORD()
raise DatabaseError, str(self.resultErrCode)+' '+self.resultErrText
self.serverStatementHandle=-1 #not connected
def _resultSetClose(self):
if self.resultSet:
self._Con.marshalBuffer.clearToSend()
self._Con.marshalBuffer.putFunction(_SQL_API_SQLCLOSECURSOR)
self._Con.marshalBuffer.putSQLHSTMT(self.serverStatementHandle) #pass server statement ref
if self.prepared:
self._Con.marshalBuffer.putSQLSMALLINT(0) #keep server plan
else:
self._Con.marshalBuffer.putSQLSMALLINT(1) #remove server plan
if self._Con.marshalBuffer.send()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
#Wait for response
if self._Con.marshalBuffer.read()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
functionId=self._Con.marshalBuffer.getFunction()
if functionId!=_SQL_API_SQLCLOSECURSOR:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
self.resultCode=self._Con.marshalBuffer.getRETCODE()
#if error, then get error details: local-number, default-text
self.errCount=self._Con.marshalBuffer.getSQLINTEGER() #error count
if self.resultCode==_SQL_ERROR:
for err in range(self.errCount):
self.resultErrCode=self._Con.marshalBuffer.getSQLINTEGER()
self.resultErrText=self._Con.marshalBuffer.getpUCHAR_SWORD()
raise DatabaseError, str(self.resultErrCode)+' '+self.resultErrText
def _doPrepare(self,sql):
self.lastSQL=sql
#call server prepare
self._Con.marshalBuffer.clearToSend()
self._Con.marshalBuffer.putFunction(_SQL_API_SQLPREPARE)
self._Con.marshalBuffer.putSQLHSTMT(self.serverStatementHandle)
self._Con.marshalBuffer.putpUCHAR_SDWORD(sql)
if self._Con.marshalBuffer.send()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
#Wait for response
if self._Con.marshalBuffer.read()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
functionId=self._Con.marshalBuffer.getFunction()
if functionId!=_SQL_API_SQLPREPARE:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
self.resultCode=self._Con.marshalBuffer.getRETCODE()
#if error, then get error details: local-number, default-text
self.errCount=self._Con.marshalBuffer.getSQLINTEGER() #error count
if self.resultCode==_SQL_ERROR:
for err in range(self.errCount):
self.resultErrCode=self._Con.marshalBuffer.getSQLINTEGER()
self.resultErrText=self._Con.marshalBuffer.getpUCHAR_SWORD()
#raise later...
resSet=self._Con.marshalBuffer.getSQLUSMALLINT()
#Remember this for future state changes
if resSet==_SQL_TRUE:
self.resultSet=True
else:
self.resultSet=False
if self.resultCode==_SQL_ERROR:
raise ProgrammingError, str(self.resultErrCode)+' '+self.resultErrText
if self.resultSet:
#Now get the cursor column count & definitions
self.col=[]
self.colCount=self._Con.marshalBuffer.getSQLINTEGER()
for i in range(self.colCount):
rn=self._Con.marshalBuffer.getSQLSMALLINT()
self.newcol=_columnSQL()
self.newcol.iFldNum=rn
self.newcol.colName=self._Con.marshalBuffer.getpSQLCHAR_SWORD()[:-1] #remove trailing \0
self.newcol.iFldType=self._Con.marshalBuffer.getSQLSMALLINT()
if self._Con.serverCLIversion>=93:
self.newcol.iUnits1=self._Con.marshalBuffer.getSQLINTEGER()
else:
self.newcol.iUnits1=self._Con.marshalBuffer.getSQLSMALLINT()
self.newcol.iUnits2=self._Con.marshalBuffer.getSQLSMALLINT()
self.newcol.iNullOffset=self._Con.marshalBuffer.getSQLSMALLINT()
self.col.append(self.newcol)
#Now set the description
self._description=[]
for newcol in self.col:
if newcol.iFldType==_SQL_NUMERIC or newcol.iFldType==_SQL_DECIMAL:
dsize=newcol.iUnits1+newcol.iUnits2+1
isize=newcol.iUnits1+newcol.iUnits2
elif newcol.iFldType==_SQL_SMALLINT:
dsize=5
isize=2
elif newcol.iFldType==_SQL_INTEGER:
dsize=10
isize=4
elif newcol.iFldType==_SQL_REAL:
dsize=7
isize=4
elif newcol.iFldType==_SQL_FLOAT or newcol.iFldType==_SQL_DOUBLE:
dsize=15
isize=8
elif newcol.iFldType==_SQL_TYPE_DATE:
dsize=10
isize=4
elif newcol.iFldType==_SQL_TYPE_TIME:
dsize=8
if newcol.iUnits2>0:
dsize=9+newcol.iUnits2
isize=8
elif newcol.iFldType==_SQL_TYPE_TIMESTAMP:
dsize=19
if newcol.iUnits2>0:
dsize=20+newcol.iUnits2
isize=12
else:
dsize=newcol.iUnits1
isize=newcol.iUnits1
self._description.append((newcol.colName, newcol.iFldType,
dsize, isize, newcol.iUnits1, newcol.iUnits2, None))
else:
#no result set
self._description=None
self.colCount=0
#Now get the param count & definitions
self.paramCount=self._Con.marshalBuffer.getSQLINTEGER()
for i in range(self.paramCount):
rn=self._Con.marshalBuffer.getSQLSMALLINT()
self.newparam=_paramSQL()
self.newparam.iParamNum=rn
self.newparam.colName=self._Con.marshalBuffer.getpSQLCHAR_SWORD()
self.newparam.iDataType=self._Con.marshalBuffer.getSQLSMALLINT()
self.newparam.iArgType=_ptInput #default
if self._Con.serverCLIversion>=93:
self.newparam.iUnits1=self._Con.marshalBuffer.getSQLINTEGER()
else:
self.newparam.iUnits1=self._Con.marshalBuffer.getSQLSMALLINT()
self.newparam.iUnits2=self._Con.marshalBuffer.getSQLSMALLINT()
x=self._Con.marshalBuffer.getSQLSMALLINT()
self.param.append(self.newparam)
#Now auto-bind all the columns
for i in range(self.colCount):
self._Con.marshalBuffer.clearToSend()
self._Con.marshalBuffer.putFunction(_SQL_API_SQLSETDESCFIELD)
self._Con.marshalBuffer.putSQLHSTMT(self.serverStatementHandle) #pass server statement ref
self._Con.marshalBuffer.putSQLSMALLINT(_SQL_ATTR_APP_ROW_DESC)
self._Con.marshalBuffer.putSQLSMALLINT(i+1) #=colRef(-1) on the server
self._Con.marshalBuffer.putSQLSMALLINT(_SQL_DESC_DATA_POINTER)
self._Con.marshalBuffer.putSQLPOINTER(1) #= 0=unbound, else bound
self._Con.marshalBuffer.putSQLINTEGER(0)
if self._Con.marshalBuffer.send()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
#Wait for response
if self._Con.marshalBuffer.read()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
functionId=self._Con.marshalBuffer.getFunction()
if functionId!=_SQL_API_SQLSETDESCFIELD:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
self.resultCode=self._Con.marshalBuffer.getRETCODE()
#if error, then get error details: local-number, default-text
self.errCount=self._Con.marshalBuffer.getSQLINTEGER() #error count
if self.resultCode==_SQL_ERROR:
for err in range(self.errCount):
self.resultErrCode=self._Con.marshalBuffer.getSQLINTEGER()
self.resultErrText=self._Con.marshalBuffer.getpUCHAR_SWORD()
#raise DatabaseError, str(self.resultErrCode)+' '+self.resultErrText
def _doExecute(self, parameters):
self._Con.marshalBuffer.clearToSend()
self._Con.marshalBuffer.putFunction(_SQL_API_SQLEXECUTE)
self._Con.marshalBuffer.putSQLHSTMT(self.serverStatementHandle) #pass server statement ref
#Write row count
self._Con.marshalBuffer.putSQLUINTEGER(1)
for row in range(1,2):
#Now send the param count & data for this row
if parameters is None:
self._Con.marshalBuffer.putSQLINTEGER(0)
else:
self._Con.marshalBuffer.putSQLINTEGER(len(parameters))
for i in range(len(parameters)):
self._Con.marshalBuffer.putSQLSMALLINT((i+1))
#Put the data
#Put the null flag
tempNull=_SQL_FALSE #default
if parameters[i] is None:
tempNull=_SQL_TRUE
self._Con.marshalBuffer.putSQLSMALLINT(tempNull)
#Note: we only send length+data if not null
if tempNull==_SQL_FALSE:
if isinstance(parameters[i],BinaryString):
self._Con.marshalBuffer.putpDataSDWORD(str(parameters[i])) #omit \0 if BLOB
else :
self._Con.marshalBuffer.putpDataSDWORD(str(parameters[i])+chr(0))
if self._Con.marshalBuffer.send()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
#Wait for response
if self._Con.marshalBuffer.read()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
functionId=self._Con.marshalBuffer.getFunction()
if functionId!=_SQL_API_SQLEXECUTE:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
self.resultCode=self._Con.marshalBuffer.getRETCODE()
#if error, then get error details: local-number, default-text
self.errCount=self._Con.marshalBuffer.getSQLINTEGER() #error count
if self.resultCode==_SQL_ERROR:
for err in range(self.errCount):
self.resultErrCode=self._Con.marshalBuffer.getSQLINTEGER()
self.resultErrText=self._Con.marshalBuffer.getpUCHAR_SWORD()
raise DatabaseError, str(self.resultErrCode)+' '+self.resultErrText
#Get the row count - only valid for insert/update/delete
self._affectedRowCount=self._Con.marshalBuffer.getSQLINTEGER()
if self._Con.serverCLIversion>=92:
#Now get any late (post-prepare) resultSet definition, i.e. for stored procedure return cursors
#False here doesn't mean we have no result set, it means we should use the details from SQLprepare
lateResSet=self._Con.marshalBuffer.getSQLUSMALLINT()
#Remember this for future state changes
if lateResSet==_SQL_TRUE:
self.resultSet=True
#else leave resultSet as was
if lateResSet==_SQL_TRUE:
#Now get the cursor column count & definitions
self.col=[]
self.colCount=self._Con.marshalBuffer.getSQLINTEGER()
for i in range(self.colCount):
rn=self._Con.marshalBuffer.getSQLSMALLINT()
self.newcol=_columnSQL()
self.newcol.iFldNum=rn
self.newcol.colName=self._Con.marshalBuffer.getpSQLCHAR_SWORD()[:-1] #remove trailing \0
self.newcol.iFldType=self._Con.marshalBuffer.getSQLSMALLINT()
if self._Con.serverCLIversion>=93:
self.newcol.iUnits1=self._Con.marshalBuffer.getSQLINTEGER()
else:
self.newcol.iUnits1=self._Con.marshalBuffer.getSQLSMALLINT()
self.newcol.iUnits2=self._Con.marshalBuffer.getSQLSMALLINT()
self.newcol.iNullOffset=self._Con.marshalBuffer.getSQLSMALLINT()
self.col.append(self.newcol)
#Now set the description
self._description=[]
for rn,newcol in self.col:
if newcol.iFldType==_SQL_NUMERIC or newcol.iFldType==_SQL_DECIMAL:
dsize=newcol.iUnits1+newcol.iUnits2+1
isize=newcol.iUnits1+newcol.iUnits2
elif newcol.iFldType==_SQL_SMALLINT:
dsize=5
isize=2
elif newcol.iFldType==_SQL_INTEGER:
dsize=10
isize=4
elif newcol.iFldType==_SQL_REAL:
dsize=7
isize=4
elif newcol.iFldType==_SQL_FLOAT or newcol.iFldType==_SQL_DOUBLE:
dsize=15
isize=8
elif newcol.iFldType==_SQL_TYPE_DATE:
dsize=10
isize=4
elif newcol.iFldType==_SQL_TYPE_TIME:
dsize=8
if newcol.iUnits2>0:
dsize=9+newcol.iUnits2
isize=8
elif newcol.iFldType==_SQL_TYPE_TIMESTAMP:
dsize=19
if newcol.iUnits2>0:
dsize=20+newcol.iUnits2
isize=12
else:
dsize=newcol.iUnits1
isize=newcol.iUnits1
self._description.append((newcol.colName, newcol.iFldType,
dsize, isize, newcol.iUnits1, newcol.iUnits2, None))
#else no late result set: leave as was (i.e. don't zeroise self.description)
#else young server cannot handle this
if self.resultCode==_SQL_SUCCESS or self.resultCode==_SQL_SUCCESS_WITH_INFO:
#we SQLendTran now if in autocommit mode & if not select/result-set
if not self.resultSet and self._Con._Autocommit:
self._Con.commit()
elif self.resultCode==_SQL_NEED_DATA:
if self.prepared:
rn=self._Con.marshalBuffer.getSQLSMALLINT() #this is the parameter id that's missing
raise InterfaceError, str(_seMissingParameter)+' '+_seMissingParameterText
def execute(self, operation=None, parameters=None):
'''Execute the specified SQL operation, possibly opening a result set.
'''
self._doPrepare(operation)
self._doExecute(parameters)
return None
def executemany(self, operation=None, seq_of_parameters=None):
'''Repeatedly execute the specified SQL operation, once for each set of
parameters in the sequence.
This is more efficient than repeatedly calling the execute method.
'''
self._doPrepare(operation)
self.prepared=True
for parameters in seq_of_parameters:
if self.resultSet: #close any existing query result set on this cursor before we re-execute
self._resultSetClose()
last=self._doExecute(parameters)
return last
def callproc(self, procname, parameters=None):
'''Call the specified stored procedure with the parameters.
May return a result set accessible using the fetchXXX methods.
'''
return self.execute('CALL '+procname+replace(replace(str(parameters),'[','('),']',')'))
def _setArraySize(self, arraySize=1):
'''Tell the server how many rows to return per fetch.
'''
self._Con.marshalBuffer.clearToSend()
self._Con.marshalBuffer.putFunction(_SQL_API_SQLSETDESCFIELD)
self._Con.marshalBuffer.putSQLHSTMT(self.serverStatementHandle)
self._Con.marshalBuffer.putSQLSMALLINT(_SQL_ATTR_APP_ROW_DESC)
self._Con.marshalBuffer.putSQLSMALLINT(0)
self._Con.marshalBuffer.putSQLSMALLINT(_SQL_DESC_ARRAY_SIZE)
self._Con.marshalBuffer.putSQLUINTEGER(arraySize)
self._Con.marshalBuffer.putSQLINTEGER(0) #bufferLength = n/a here
if self._Con.marshalBuffer.send()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
#Wait for response
if self._Con.marshalBuffer.read()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
functionId=self._Con.marshalBuffer.getFunction()
if functionId!=_SQL_API_SQLSETDESCFIELD:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
self.resultCode=self._Con.marshalBuffer.getRETCODE()
#if error, then get error details: local-number, default-text
self.errCount=self._Con.marshalBuffer.getSQLINTEGER() #error count
if self.resultCode==_SQL_ERROR:
for err in range(self.errCount):
self.resultErrCode=self._Con.marshalBuffer.getSQLINTEGER()
self.resultErrText=self._Con.marshalBuffer.getpUCHAR_SWORD()
raise DatabaseError, str(self.resultErrCode)+' '+self.resultErrText
#record the latest value
self.lastArraySize=arraySize
def _fetch(self, arraySize=None):
if self.resultSet:
res=[]
if arraySize!=None and arraySize!=self.lastArraySize:
self._setArraySize(arraySize)
#call server fetchScroll
self._Con.marshalBuffer.clearToSend()
self._Con.marshalBuffer.putFunction(_SQL_API_SQLFETCHSCROLL)
self._Con.marshalBuffer.putSQLHSTMT(self.serverStatementHandle)
self._Con.marshalBuffer.putSQLSMALLINT(_SQL_FETCH_NEXT)
self._Con.marshalBuffer.putSQLINTEGER(0)
if self._Con.marshalBuffer.send()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
#Wait for response
if self._Con.marshalBuffer.read()!=_ok:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
functionId=self._Con.marshalBuffer.getFunction()
if functionId!=_SQL_API_SQLFETCHSCROLL:
raise ConnectionError, str(_seConnectionFailed)+' '+_seConnectionFailedText
#resultCode comes later: first we retrieve any result data
#Read row count
rowCount=self._Con.marshalBuffer.getSQLUINTEGER()
for row in range(rowCount):
rowres=[]
#Now get the col count & data for this row
self.colCount=self._Con.marshalBuffer.getSQLINTEGER()
for i in range(self.colCount):
rn=self._Con.marshalBuffer.getSQLSMALLINT()
if rn<=self.colCount:
#Get the null flag
tempNull=self._Con.marshalBuffer.getSQLSMALLINT()
if tempNull==_SQL_TRUE:
rowres.append(None)
else:
#Note: we only get length+data if not null
self.col[i].data=self._Con.marshalBuffer.getpDataSDWORD()
#Convert the raw data to Python data
if self.col[i].iFldType==_SQL_CHAR or self.col[i].iFldType==_SQL_VARCHAR:
rowres.append(self.col[i].data)
elif self.col[i].iFldType==_SQL_NUMERIC or self.col[i].iFldType==_SQL_DECIMAL:
if have_fixedpoint:
fp=str(struct.unpack('<q',self.col[i].data)[0])
fp=fp[:len(fp)-self.col[i].iUnits2]+'.'+fp[len(fp)-self.col[i].iUnits2:]
rowres.append(FixedPoint(fp,self.col[i].iUnits2))
else:
rowres.append((struct.unpack('<q',self.col[i].data)[0]) / float(10**self.col[i].iUnits2)) #i.e. shift scale decimal places to the right
elif self.col[i].iFldType==_SQL_INTEGER:
rowres.append(struct.unpack('<i',self.col[i].data)[0])
elif self.col[i].iFldType==_SQL_SMALLINT:
rowres.append(struct.unpack('<h',self.col[i].data)[0])
elif self.col[i].iFldType==_SQL_FLOAT or self.col[i].iFldType==_SQL_REAL or self.col[i].iFldType==_SQL_DOUBLE:
rowres.append(struct.unpack('<d',self.col[i].data)[0])
elif self.col[i].iFldType==_SQL_TYPE_DATE:
p=struct.unpack(_sqlDate,self.col[i].data)
rowres.append(datetime.date(p[0],p[1],p[2]))
elif self.col[i].iFldType==_SQL_TYPE_TIME:
p=struct.unpack(_sqlTime,self.col[i].data)
rowres.append(datetime.time(p[0],p[1],int(p[2] / float(10**_TIME_MAX_SCALE)))) #todo Adjust the scale? p[3]
elif self.col[i].iFldType==_SQL_TYPE_TIMESTAMP:
p=struct.unpack(_sqlTimestamp,self.col[i].data)
rowres.append(datetime.datetime(p[0],p[1],p[2],p[3],p[4],int(p[5] / float(10**_TIME_MAX_SCALE)))) #todo Adjust the scale? p[6]
elif self.col[i].iFldType==_SQL_LONGVARCHAR or self.col[i].iFldType==_SQL_LONGVARBINARY:
rowres.append(self.col[i].data)
#todo SQL_INTERVAL etc.
else:
rowres.append('?') #todo use raw data or None instead?
else:
raise OperationalError, str(_seInvalidColumnIndex)+' '+_seInvalidColumnIndexText
#get row status
sqlRowStatus=self._Con.marshalBuffer.getSQLUSMALLINT()
if sqlRowStatus==_SQL_ROW_NOROW:
break #-> no more data
if arraySize>1:
res.append(tuple(rowres))
else:
res=tuple(rowres)
self.resultCode=self._Con.marshalBuffer.getRETCODE()
if self.resultCode==_SQL_NO_DATA and arraySize==1:
res=None #-> no more data
#if error, then get error details: local-number, default-text
self.errCount=self._Con.marshalBuffer.getSQLINTEGER() #error count
if self.resultCode==_SQL_ERROR:
for err in range(self.errCount):
self.resultErrCode=self._Con.marshalBuffer.getSQLINTEGER()
self.resultErrText=self._Con.marshalBuffer.getpUCHAR_SWORD()
raise DatabaseError, str(self.resultErrCode)+' '+self.resultErrText
return res
else:
raise InterfaceError, str(_seResultSetNotOpen)+' '+_seResultSetNotOpenText
def fetchone(self):
'''Fetch the next row from the cursor's result set.
'''
return self._fetch(1)
def fetchmany(self, size=None):
'''Fetch a number of rows from the cursor's result set.
'''
if size is None:
size=self.lastArraySize
return self._fetch(size)
def fetchall(self):
'''Fetch all the remaining rows from the cursor's result set.
'''
res=[]
while 1:
r=self.fetchone()
if r is None:
break
res.append(r)
return res
def _getaffectedRowCount(self):
return self._affectedRowCount
rowcount=property(_getaffectedRowCount, doc='Number of affected row(s)')
def _getdescription(self):
return self._description
def _getconnection(self):
warnings.warn('DB-API extension cursor.connection used')
return self._Con
description=property(_getdescription, doc='Column description(s)')
def _getarraysize(self):
return self.lastArraySize
arraysize=property(_getarraysize, _setArraySize, doc='Number of rows to fetch with fetchmany()')
def __iter__(self):
return self
def next(self):
x=self.fetchone()
if x is None:
raise StopIteration
return x
def __del__(self):
self.close()
#Column/Parameter classes -----------------------------------------------------
class _columnSQL:
def __init__(self):
self.iFldNum=None
self.iFldType=None
self.iUnits1=None
self.iUnits2=None
self.iNullOffset=None
self.colName=None
self.data=None
class _paramSQL:
def __init__(self):
self.iParamNum=None
self.colName=None
self.iDataType=None
self.iArgType=None
self.iUnits1=None
self.iUnits2=None
self.buffer=None
self.bufferLen=None
self.isNull=None
_clientCLIversion =100 #client parameter passing version
_CLI_ODBC=1
_CLI_JDBC=2
_CLI_DBEXPRESS=3
_CLI_ADO_NET=4
_CLI_PYTHON_DBAPI=5
_DriverName='ThinkSQL'
_DriverVersion='1.03.01'
__version__ = 1, 03, 01
_DriverMajorVersion=1
_DriverMinorVersion=03
_ok=0
_fail=-1
_failString=''
_stateClosed=0
_stateOpen=1
_sizeof_short=2
_sizeof_int=4
_sizeof_long=8
_sizeof_float=4
_sizeof_double=8
_sizeof_byte=8 #in bits
_sizeof_date=4
_sizeof_dateY=2
_sizeof_dateM=1
_sizeof_dateD=1
_sizeof_time=7
_sizeof_timeH=1
_sizeof_timeM=1
_sizeof_timeS=4
_sizeof_timeSc=1
_TIME_MAX_SCALE=6
_MAX_COL_PER_TABLE=300
_MAX_PARAM_PER_QUERY=300
_SQL_FALSE =0
_SQL_TRUE =1
#parameter types
_ptInput = 0
_ptOutput = 1
_EscapeChar='\\'
_SQL_ERROR=-1
_SQL_ERROR2=_SQL_ERROR
_SQL_SUCCESS=0
_SQL_SUCCESS_WITH_INFO=1
_SQL_STILL_EXECUTING=2
_SQL_NEED_DATA=99
_SQL_NO_DATA=100
_SQL_CHAR =1
_SQL_NUMERIC =2
_SQL_DECIMAL =3
_SQL_INTEGER =4
_SQL_SMALLINT =5
_SQL_FLOAT =6
_SQL_REAL =7
_SQL_DOUBLE =8
_SQL_DATETIME =9
_SQL_INTERVAL =10
_SQL_VARCHAR =12
_SQL_TYPE_DATE =91
_SQL_TYPE_TIME =92
_SQL_TYPE_TIMESTAMP =93
_SQL_LONGVARCHAR =-1
#SQL_BINARY =-2
#SQL_VARBINARY =-3
_SQL_LONGVARBINARY =-4
#future use: SQL_BIGINT =-5
_SQL_API_SQLCONNECT =7
_SQL_API_SQLDISCONNECT =9
_SQL_API_SQLEXECUTE =12
_SQL_API_SQLPREPARE =19
_SQL_API_SQLGETDATA =43
_SQL_API_SQLGETINFO =45
_SQL_API_SQLALLOCHANDLE =1001
_SQL_API_SQLCLOSECURSOR =1003
_SQL_API_SQLENDTRAN =1005
_SQL_API_SQLFREEHANDLE =1006
_SQL_API_SQLSETDESCFIELD =1017
_SQL_API_SQLFETCHSCROLL =1021
_SQL_ATTR_APP_ROW_DESC =10010
_SQL_DESC_ARRAY_SIZE =20