-
Notifications
You must be signed in to change notification settings - Fork 26
/
fbcore.py
5348 lines (4940 loc) · 238 KB
/
fbcore.py
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
#coding:utf-8
#
# PROGRAM/MODULE: fdb
# FILE: fbcore.py
# DESCRIPTION: Python driver for Firebird
# CREATED: 8.10.2011
#
# Software distributed under the License is distributed AS IS,
# WITHOUT WARRANTY OF ANY KIND, either express or implied.
# See the License for the specific language governing rights
# and limitations under the License.
#
# The Original Code was created by Pavel Cisar
#
# Copyright (c) 2011 Pavel Cisar <pcisar@users.sourceforge.net>
# and all contributors signed below.
#
# All Rights Reserved.
# Contributor(s): Philippe Makowski <pmakowski@ibphoenix.fr>
# ______________________________________.
#
# See LICENSE.TXT for details.
import sys
import os
import ctypes
import struct
import time
import datetime
import decimal
import weakref
import threading
from . import ibase
from . import schema
from . import monitor
from . import utils
try:
# Python 2
from itertools import izip_longest
except ImportError:
# Python 3
from itertools import zip_longest as izip_longest
from fdb.ibase import (frb_info_att_charset, isc_dpb_activate_shadow,
isc_dpb_address_path, isc_dpb_allocation, isc_dpb_begin_log,
isc_dpb_buffer_length, isc_dpb_cache_manager, isc_dpb_cdd_pathname,
isc_dpb_connect_timeout, isc_dpb_damaged, isc_dpb_dbkey_scope,
isc_dpb_debug, isc_dpb_delete_shadow, isc_dpb_disable_journal,
isc_dpb_disable_wal, isc_dpb_drop_walfile,
isc_dpb_dummy_packet_interval, isc_dpb_enable_journal,
isc_dpb_encrypt_key, isc_dpb_force_write, isc_dpb_garbage_collect,
isc_dpb_gbak_attach, isc_dpb_gfix_attach, isc_dpb_gsec_attach,
isc_dpb_gstat_attach, isc_dpb_interp, isc_dpb_journal,
isc_dpb_lc_ctype, isc_dpb_lc_messages, isc_dpb_license,
isc_dpb_no_garbage_collect, isc_dpb_no_reserve,
isc_dpb_num_buffers, isc_dpb_number_of_users, isc_dpb_old_dump_id,
isc_dpb_old_file, isc_dpb_old_file_size, isc_dpb_old_num_files,
isc_dpb_old_start_file, isc_dpb_old_start_page,
isc_dpb_old_start_seqno, isc_dpb_online, isc_dpb_online_dump,
isc_dpb_overwrite, isc_dpb_page_size, isc_dpb_password,
isc_dpb_password_enc, isc_dpb_quit_log, isc_dpb_reserved,
isc_dpb_sec_attach, isc_dpb_set_db_charset,
isc_dpb_set_db_readonly, isc_dpb_set_db_sql_dialect,
isc_dpb_set_page_buffers, isc_dpb_shutdown, isc_dpb_shutdown_delay,
isc_dpb_sql_dialect, isc_dpb_sql_role_name, isc_dpb_sweep,
isc_dpb_sweep_interval, isc_dpb_sys_user_name,
isc_dpb_sys_user_name_enc, isc_dpb_trace, isc_dpb_user_name,
isc_dpb_verify, isc_dpb_version1, isc_dpb_wal_backup_dir,
isc_dpb_wal_bufsize, isc_dpb_wal_chkptlen,
isc_dpb_wal_grp_cmt_wait, isc_dpb_wal_numbufs,
isc_dpb_working_directory, isc_dpb_no_db_triggers, isc_dpb_nolinger,
isc_info_active_tran_count, isc_info_end, isc_info_truncated,
isc_info_sql_stmt_type, isc_info_sql_get_plan, isc_info_sql_records,
isc_info_req_select_count, isc_info_req_insert_count,
isc_info_req_update_count, isc_info_req_delete_count,
isc_info_blob_total_length, isc_info_blob_max_segment,
fb_info_page_contents,
isc_info_active_transactions, isc_info_allocation,
isc_info_attachment_id, isc_info_backout_count,
isc_info_base_level, isc_info_bpage_errors, isc_info_creation_date,
isc_info_cur_log_part_offset, isc_info_cur_logfile_name,
isc_info_current_memory,
isc_info_db_class, isc_info_db_id, isc_info_db_provider,
isc_info_db_read_only, isc_info_db_size_in_pages,
isc_info_db_sql_dialect, isc_info_delete_count,
isc_info_dpage_errors, isc_info_expunge_count, isc_info_fetches,
isc_info_firebird_version, isc_info_forced_writes,
isc_info_implementation, isc_info_insert_count,
isc_info_ipage_errors, isc_info_isc_version, isc_info_license,
isc_info_limbo, isc_info_logfile, isc_info_marks,
isc_info_max_memory, isc_info_next_transaction,
isc_info_no_reserve, isc_info_num_buffers,
isc_info_num_wal_buffers, isc_info_ods_minor_version,
isc_info_ods_version, isc_info_oldest_active,
isc_info_oldest_snapshot, isc_info_oldest_transaction,
isc_info_page_errors, isc_info_page_size, isc_info_ppage_errors,
isc_info_purge_count, isc_info_read_idx_count,
isc_info_read_seq_count, isc_info_reads, isc_info_record_errors,
isc_info_set_page_buffers, isc_info_sql_stmt_commit,
isc_info_sql_stmt_ddl, isc_info_sql_stmt_delete,
isc_info_sql_stmt_exec_procedure, isc_info_sql_stmt_get_segment,
isc_info_sql_stmt_insert, isc_info_sql_stmt_put_segment,
isc_info_sql_stmt_rollback, isc_info_sql_stmt_savepoint,
isc_info_sql_stmt_select, isc_info_sql_stmt_select_for_upd,
isc_info_sql_stmt_set_generator, isc_info_sql_stmt_start_trans,
isc_info_sql_stmt_update, isc_info_sweep_interval,
isc_info_tpage_errors, isc_info_tra_access,
isc_info_tra_concurrency, isc_info_tra_consistency,
isc_info_tra_id, isc_info_tra_isolation, isc_info_tra_lock_timeout,
isc_info_tra_no_rec_version, isc_info_tra_oldest_active,
isc_info_tra_oldest_interesting, isc_info_tra_oldest_snapshot,
isc_info_tra_read_committed, isc_info_tra_readonly,
isc_info_tra_readwrite, isc_info_tra_rec_version, fb_info_tra_dbpath,
isc_info_update_count, isc_info_user_names, isc_info_version,
isc_info_wal_avg_grpc_size, isc_info_wal_avg_io_size,
isc_info_wal_buffer_size, isc_info_wal_ckpt_length,
isc_info_wal_cur_ckpt_interval, isc_info_wal_grpc_wait_usecs,
isc_info_wal_num_commits, isc_info_wal_num_io,
isc_info_wal_prv_ckpt_fname, isc_info_wal_prv_ckpt_poffset,
isc_info_wal_recv_ckpt_fname, isc_info_wal_recv_ckpt_poffset,
isc_info_window_turns, isc_info_writes, isc_tpb_autocommit,
isc_tpb_commit_time, isc_tpb_concurrency, isc_tpb_consistency,
isc_tpb_exclusive, isc_tpb_ignore_limbo, isc_tpb_lock_read,
isc_tpb_lock_timeout, isc_tpb_lock_write, isc_tpb_no_auto_undo,
isc_tpb_no_rec_version, isc_tpb_nowait, isc_tpb_protected,
isc_tpb_read, isc_tpb_read_committed, isc_tpb_rec_version,
isc_tpb_restart_requests, isc_tpb_shared, isc_tpb_verb_time,
isc_tpb_version3, isc_tpb_wait, isc_tpb_write,
b, s, ord2, int2byte, mychr, mybytes, myunicode, mylong, StringType,
IntType, LongType, FloatType, ListType, UnicodeType, TupleType, xrange,
charset_map,
#isc_sqlcode, isc_sql_interprete, fb_interpret, isc_dsql_execute_immediate,
XSQLDA_PTR, ISC_SHORT, ISC_LONG, ISC_SCHAR, ISC_UCHAR, ISC_QUAD,
SHRT_MIN, SHRT_MAX, USHRT_MAX, INT_MIN, INT_MAX, LONG_MIN, LONG_MAX,
SQL_TEXT, SQL_VARYING, SQL_SHORT, SQL_LONG, SQL_FLOAT, SQL_DOUBLE,
SQL_D_FLOAT, SQL_TIMESTAMP, SQL_BLOB, SQL_ARRAY, SQL_QUAD, SQL_TYPE_TIME,
SQL_TYPE_DATE, SQL_INT64, SQL_BOOLEAN, SUBTYPE_NUMERIC, SUBTYPE_DECIMAL,
MAX_BLOB_SEGMENT_SIZE, ISC_INT64,
XSQLVAR, ISC_TEB, RESULT_VECTOR, ISC_STATUS, ISC_STATUS_ARRAY, ISC_STATUS_PTR,
ISC_EVENT_CALLBACK, ISC_ARRAY_DESC,
blr_varying, blr_varying2, blr_text, blr_text2, blr_short, blr_long,
blr_int64, blr_float, blr_d_float, blr_double, blr_timestamp, blr_sql_date,
blr_sql_time,
SQLDA_version1, isc_segment,
isc_db_handle, isc_tr_handle, isc_stmt_handle, isc_blob_handle,
fbclient_API,
)
PYTHON_MAJOR_VER = sys.version_info[0]
__version__ = '1.6'
apilevel = '2.0'
threadsafety = 1
paramstyle = 'qmark'
def load_api(fb_library_name=None):
"""Initializes bindings to Firebird Client Library unless they are already initialized.
Called automatically by :func:`fdb.connect` and :func:`fdb.create_database`.
:param string fb_library_name: (optional) Path to Firebird Client Library.
When it's not specified, FDB does its best to locate appropriate client library.
:returns: :class:`fdb.ibase.fbclient_API` instance.
"""
if not hasattr(sys.modules[__name__],'api'):
setattr(sys.modules[__name__],'api',fbclient_API(fb_library_name))
return getattr(sys.modules[__name__],'api')
# Exceptions required by Python Database API
class Warning(Exception):
"""Exception raised for important warnings like data
truncations while inserting, etc."""
pass
class Error(Exception):
"""Exception that is the base class of all other error
exceptions. You can use this to catch all errors with one
single 'except' statement. Warnings are not considered
errors and thus should not use this class as base."""
pass
class InterfaceError(Error):
"""Exception raised for errors that are related to the
database interface rather than the database itself."""
pass
class DatabaseError(Error):
"Exception raised for errors that are related to the database."
pass
#def __init__(self,msg, sqlcode=0,error_code=0):
#self.sqlcode = sqlcode
#self.error_code = error_code
#self.msg = msg
class DataError(DatabaseError):
"""Exception raised for errors that are due to problems with
the processed data like division by zero, numeric value
out of range, etc."""
pass
class OperationalError(DatabaseError):
"""Exception raised for errors that are related to the
database's operation and not necessarily under the control
of the programmer, e.g. an unexpected disconnect occurs,
the data source name is not found, a transaction could not
be processed, a memory allocation error occurred during
processing, etc."""
pass
class IntegrityError(DatabaseError):
"""Exception raised when the relational integrity of the
database is affected, e.g. a foreign key check fails."""
pass
class InternalError(DatabaseError):
"""Exception raised when the database encounters an internal
error, e.g. the cursor is not valid anymore, the
transaction is out of sync, etc."""
pass
class ProgrammingError(DatabaseError):
"""Exception raised for programming errors, e.g. table not
found or already exists, syntax error in the SQL
statement, wrong number of parameters specified, etc."""
pass
class NotSupportedError(DatabaseError):
"""Exception raised in case a method or database API was used
which is not supported by the database"""
pass
class TransactionConflict(DatabaseError):
pass
# Named positional constants to be used as indices into the description
# attribute of a cursor (these positions are defined by the DB API spec).
# For example:
# nameOfFirstField = cursor.description[0][kinterbasdb.DESCRIPTION_NAME]
DESCRIPTION_NAME = 0
DESCRIPTION_TYPE_CODE = 1
DESCRIPTION_DISPLAY_SIZE = 2
DESCRIPTION_INTERNAL_SIZE = 3
DESCRIPTION_PRECISION = 4
DESCRIPTION_SCALE = 5
DESCRIPTION_NULL_OK = 6
# Types Required by Python DB-API 2.0
def Date(year, month, day):
return datetime.date(year, month, day)
def Time(hour, minite, second):
return datetime.time(hour, minite, second)
def DateFromTicks(ticks):
return apply(Date, time.localtime(ticks)[:3])
def TimeFromTicks(ticks):
return apply(Time, time.localtime(ticks)[3:6])
def TimestampFromTicks(ticks):
return apply(Timestamp, time.localtime(ticks)[:6])
def Binary(b):
return b
class DBAPITypeObject:
def __init__(self, *values):
self.values = values
def __cmp__(self, other):
if other in self.values:
return 0
if other < self.values:
return 1
else:
return -1
STRING = DBAPITypeObject(str)
if PYTHON_MAJOR_VER == 3:
BINARY = DBAPITypeObject(bytes)
else:
BINARY = DBAPITypeObject(str)
NUMBER = DBAPITypeObject(int, decimal.Decimal)
DATETIME = DBAPITypeObject(datetime.datetime, datetime.date, datetime.time)
ROWID = DBAPITypeObject()
_FS_ENCODING = sys.getfilesystemencoding()
DIST_TRANS_MAX_DATABASES = 16
def bs(byte_array):
return bytes(byte_array) if PYTHON_MAJOR_VER == 3 else ''.join((chr(c) for c in byte_array))
ISOLATION_LEVEL_READ_COMMITED_LEGACY = bs([isc_tpb_version3,
isc_tpb_write,
isc_tpb_wait,
isc_tpb_read_committed,
isc_tpb_no_rec_version])
ISOLATION_LEVEL_READ_COMMITED = bs([isc_tpb_version3,
isc_tpb_write,
isc_tpb_wait,
isc_tpb_read_committed,
isc_tpb_rec_version])
ISOLATION_LEVEL_REPEATABLE_READ = bs([isc_tpb_version3,
isc_tpb_write,
isc_tpb_wait,
isc_tpb_concurrency])
ISOLATION_LEVEL_SNAPSHOT = ISOLATION_LEVEL_REPEATABLE_READ
ISOLATION_LEVEL_SERIALIZABLE = bs([isc_tpb_version3,
isc_tpb_write,
isc_tpb_wait,
isc_tpb_consistency])
ISOLATION_LEVEL_SNAPSHOT_TABLE_STABILITY = ISOLATION_LEVEL_SERIALIZABLE
ISOLATION_LEVEL_READ_COMMITED_RO = bs([isc_tpb_version3,
isc_tpb_read,
isc_tpb_wait,
isc_tpb_read_committed,
isc_tpb_rec_version])
# ODS constants
ODS_FB_20 = 11.0
ODS_FB_21 = 11.1
ODS_FB_25 = 11.2
ODS_FB_30 = 12.0
# Translation tables
d = dir(ibase)
s = 'isc_info_db_impl_'
q = [x for x in d if x.startswith(s) and x[len(s):] != 'last_value']
#: Dictionary to map Implementation codes to names
IMPLEMENTATION_NAMES = dict(zip([getattr(ibase,x) for x in q],[x[len(s):] for x in q]))
s = 'isc_info_db_code_'
q = [x for x in d if x.startswith(s) and x[len(s):] != 'last_value']
#: Dictionary to map provider codes to names
PROVIDER_NAMES = dict(zip([getattr(ibase,x) for x in q],[x[len(s):] for x in q]))
s = 'isc_info_db_class_'
q = [x for x in d if x.startswith(s) and x[len(s):] != 'last_value']
#: Dictionary to map database class codes to names
DB_CLASS_NAMES = dict(zip([getattr(ibase,x) for x in q],[x[len(s):] for x in q]))
# Private constants
_SIZE_OF_SHORT = ctypes.sizeof(ctypes.c_short)
_tenTo = [10 ** x for x in range(20)]
if PYTHON_MAJOR_VER != 3:
del x
__xsqlda_cache = {}
__tebarray_cache = {}
_DATABASE_INFO_CODES_WITH_INT_RESULT = (
isc_info_allocation, isc_info_no_reserve, isc_info_db_sql_dialect,
isc_info_ods_minor_version, isc_info_ods_version, isc_info_page_size,
isc_info_current_memory, isc_info_forced_writes, isc_info_max_memory,
isc_info_num_buffers, isc_info_sweep_interval, isc_info_limbo,
isc_info_attachment_id, isc_info_fetches, isc_info_marks, isc_info_reads,
isc_info_writes, isc_info_set_page_buffers, isc_info_db_read_only,
isc_info_db_size_in_pages, isc_info_page_errors, isc_info_record_errors,
isc_info_bpage_errors, isc_info_dpage_errors, isc_info_ipage_errors,
isc_info_ppage_errors, isc_info_tpage_errors,frb_info_att_charset,
isc_info_oldest_transaction, isc_info_oldest_active,
isc_info_oldest_snapshot, isc_info_next_transaction,
isc_info_active_tran_count,isc_info_db_class,isc_info_db_provider,
)
_DATABASE_INFO_CODES_WITH_COUNT_RESULTS = (
isc_info_backout_count, isc_info_delete_count, isc_info_expunge_count,
isc_info_insert_count, isc_info_purge_count, isc_info_read_idx_count,
isc_info_read_seq_count, isc_info_update_count
)
_DATABASE_INFO_CODES_WITH_TIMESTAMP_RESULT = (isc_info_creation_date,)
_DATABASE_INFO__KNOWN_LOW_LEVEL_EXCEPTIONS = (isc_info_user_names, fb_info_page_contents,
isc_info_active_transactions)
def xsqlda_factory(size):
if size in __xsqlda_cache:
cls = __xsqlda_cache[size]
else:
class XSQLDA(ctypes.Structure):
pass
XSQLDA._fields_ = [
('version', ISC_SHORT),
('sqldaid', ISC_SCHAR * 8),
('sqldabc', ISC_LONG),
('sqln', ISC_SHORT),
('sqld', ISC_SHORT),
('sqlvar', XSQLVAR * size),
]
__xsqlda_cache[size] = XSQLDA
cls = XSQLDA
xsqlda = cls()
xsqlda.version = SQLDA_version1
xsqlda.sqln = size
return xsqlda
def tebarray_factory(size):
if size in __tebarray_cache:
cls = __tebarray_cache[size]
else:
cls = ISC_TEB * size
__xsqlda_cache[size] = cls
teb_array = cls()
return teb_array
buf_pointer = ctypes.POINTER(ctypes.c_char)
def is_dead_proxy(obj):
return isinstance(obj,weakref.ProxyType) and not dir(obj)
def b2u(st, charset):
"Decode to unicode if charset is defined. For conversion of result set data."
if charset:
return st.decode(charset)
else:
return st
def p3fix(st, charset):
"""For P3 convert bytes to string using connection charset, P2 as is.
For conversion of info results to native strings."""
if PYTHON_MAJOR_VER == 3:
return st.decode(charset)
else:
return st
def inc_pointer(pointer):
t = type(pointer)
p = ctypes.cast(pointer,ctypes.c_void_p)
p.value += 1
return ctypes.cast(p,t)
def bytes_to_bint(b): # Read as big endian
len_b = len(b)
if len_b == 1:
fmt = 'B'
elif len_b == 2:
fmt = '>H'
elif len_b == 4:
fmt = '>L'
elif len_b == 8:
fmt = '>Q'
else:
raise InternalError
return struct.unpack(fmt, b)[0]
def bytes_to_int(b): # Read as little endian.
len_b = len(b)
if len_b == 1:
fmt = 'b'
elif len_b == 2:
fmt = '<h'
elif len_b == 4:
fmt = '<l'
elif len_b == 8:
fmt = '<q'
else:
raise InternalError
return struct.unpack(fmt, b)[0]
def bytes_to_uint(b): # Read as little endian.
len_b = len(b)
if len_b == 1:
fmt = 'B'
elif len_b == 2:
fmt = '<H'
elif len_b == 4:
fmt = '<L'
elif len_b == 8:
fmt = '<Q'
else:
raise InternalError
return struct.unpack(fmt, b)[0]
def bint_to_bytes(val, nbytes): # Convert int value to big endian bytes.
if nbytes == 1:
fmt = 'b'
elif nbytes == 2:
fmt = '>h'
elif nbytes == 4:
fmt = '>l'
elif nbytes == 8:
fmt = '>q'
else:
raise InternalError
return struct.pack(fmt, val)
def int_to_bytes(val, nbytes): # Convert int value to little endian bytes.
if nbytes == 1:
fmt = 'b'
elif nbytes == 2:
fmt = '<h'
elif nbytes == 4:
fmt = '<l'
elif nbytes == 8:
fmt = '<q'
else:
raise InternalError
return struct.pack(fmt, val)
def uint_to_bytes(val, nbytes): # Convert int value to little endian bytes.
if nbytes == 1:
fmt = 'B'
elif nbytes == 2:
fmt = '<H'
elif nbytes == 4:
fmt = '<L'
elif nbytes == 8:
fmt = '<Q'
else:
raise InternalError
return struct.pack(fmt, val)
def db_api_error(status_vector):
return status_vector[0] == 1 and status_vector[1] > 0
def exception_from_status(error, status, preamble=None):
msglist = []
msg = ctypes.create_string_buffer(512)
if preamble:
msglist.append(preamble)
sqlcode = api.isc_sqlcode(status)
error_code = status[1]
msglist.append('- SQLCODE: %i' % sqlcode)
#isc_sql_interprete(sqlcode, msg, 512)
#if PYTHON_MAJOR_VER == 3:
#### Todo: trouble? decode from connection charset?
#msglist.append('- ' + (msg.value).decode('utf_8'))
#else:
#msglist.append('- ' + msg.value)
pvector = ctypes.cast(ctypes.addressof(status), ISC_STATUS_PTR)
while True:
result = api.fb_interpret(msg, 512, pvector)
if result != 0:
if PYTHON_MAJOR_VER == 3:
### Todo: trouble? decode from connection charset?
msglist.append('- ' + (msg.value).decode('utf_8'))
else:
msglist.append('- ' + msg.value)
else:
break
return error('\n'.join(msglist), sqlcode, error_code)
def build_dpb(user, password, sql_dialect, role, charset, buffers, force_write,
no_reserve, db_key_scope, no_gc, no_db_triggers, no_linger):
params = [int2byte(isc_dpb_version1)]
def addString(codeAsByte, s):
if PYTHON_MAJOR_VER == 3 or isinstance(s,UnicodeType):
s = s.encode(charset_map.get(charset, charset))
sLen = len(s)
if sLen >= 256:
# Because the length is denoted in the DPB by a single byte.
raise ProgrammingError("Individual component of database"
" parameter buffer is too large. Components must be less"
" than 256 bytes."
)
myformat = 'cc%ds' % sLen # like 'cc50s' for a 50-byte string
newEntry = struct.pack(myformat, int2byte(codeAsByte),
int2byte(sLen), s)
params.append(newEntry)
def addByte(codeAsByte, value):
if (not isinstance(value, (int, mylong))
or value < 0 or value > 255):
raise ProgrammingError("The value for an integer DPB code must be"
" an int or long with a value between 0 and 255."
)
newEntry = struct.pack('ccc', int2byte(codeAsByte),
b('\x01'), int2byte(value))
params.append(newEntry)
def addInt(codeAsByte, value):
if not isinstance(value, (int, mylong)):
raise ProgrammingError("The value for an integer DPB code must be"
" an int or long."
)
newEntry = struct.pack('=ccI', int2byte(codeAsByte),
b('\x04'), value)
params.append(newEntry)
if user:
addString(isc_dpb_user_name, user)
if password:
addString(isc_dpb_password, password)
if role:
addString(isc_dpb_sql_role_name, role)
if sql_dialect:
addByte(isc_dpb_sql_dialect, sql_dialect)
if charset:
addString(isc_dpb_lc_ctype, charset.upper())
if buffers:
addInt(isc_dpb_num_buffers, buffers)
if force_write:
addByte(isc_dpb_force_write, force_write)
if no_reserve:
addByte(isc_dpb_no_reserve, no_reserve)
if db_key_scope:
addByte(isc_dpb_dbkey_scope, db_key_scope)
if no_gc:
addByte(isc_dpb_no_garbage_collect, no_gc)
if no_db_triggers:
addByte(isc_dpb_no_db_triggers, no_db_triggers)
if no_linger:
addByte(isc_dpb_nolinger, no_linger)
return b('').join(params)
def connect(dsn='', user=None, password=None, host=None, port=3050, database=None,
sql_dialect=3, role=None, charset=None, buffers=None,
force_write=None, no_reserve=None, db_key_scope=None,
isolation_level=ISOLATION_LEVEL_READ_COMMITED,
connection_class=None, fb_library_name=None,
no_gc=None, no_db_triggers=None, no_linger=None):
"""
Establish a connection to database.
:param dsn: Connection string in format [host[/port]]:database
:param string user: User name. If not specified, fdb attempts to use ISC_USER envar.
:param string password: User password. If not specified, fdb attempts to use ISC_PASSWORD envar.
:param string host: Server host machine specification.
:param integer port: Port used by Firebird server **(not used)**.
:param string database: Database specification (file spec. or alias)
:param sql_dialect: SQL Dialect for connection.
:type sql_dialect): 1, 2 or 3
:param string role: User role.
:param string charset: Character set for connection.
:param integer buffers: Page case size override for connection.
:param integer force_writes: Forced writes override for connection.
:param integer no_reserve: Page space reservation override for connection.
:param integer db_key_scope: DBKEY scope override for connection.
:param isolation_level: Default transaction isolation level for connection **(not used)**.
:type isolation_level: 0, 1, 2 or 3
:param connection_class: Custom connection class
:type connection_class: subclass of :class:`Connection`
:param string fb_library_name: Full path to Firebird client library. See :func:`~fdb.load_api` for details.
:param integer no_gc: No Garbage Collection flag.
:param integer no_db_triggers: No database triggers flag (FB 2.1).
:param integer no_linger: No linger flag (FB3).
:returns: Connection to database.
:rtype: :class:`Connection` instance.
:raises ProgrammingError: For bad parameter values.
:raises DatabaseError: When connection cannot be established.
.. important::
You may specify the database using either `dns` or `database` (with optional `host`),
but not both.
Examples:
.. code-block:: python
con = fdb.connect(dsn='host:/path/database.fdb', user='sysdba', password='pass', charset='UTF8')
con = fdb.connect(host='myhost', database='/path/database.fdb', user='sysdba', password='pass', charset='UTF8')
"""
load_api(fb_library_name)
if connection_class == None:
connection_class = Connection
if not issubclass(connection_class,Connection):
raise ProgrammingError("'connection_class' must be subclass of Connection")
if not user:
user = os.environ.get('ISC_USER', None)
if not password:
password = os.environ.get('ISC_PASSWORD', None)
if sql_dialect not in [1, 2, 3]:
raise ProgrammingError("SQl Dialect must be either 1, 2 or 3")
if ((not dsn and not host and not database)
or (dsn and (host or database))
or (host and not database)
):
raise ProgrammingError(
"Must supply one of:\n"
" 1. keyword argument dsn='host:/path/to/database'\n"
" 2. both keyword arguments host='host' and"
" database='/path/to/database'\n"
" 3. only keyword argument database='/path/to/database'"
)
if not dsn:
if host and host.endswith(':'):
raise ProgrammingError("Host must not end with a colon."
" You should specify host='%s' rather than host='%s'."
% (host[:-1], host)
)
elif host:
dsn = '%s:%s' % (host, database)
else:
dsn = database
dsn = b(dsn,_FS_ENCODING)
if charset:
charset = charset.upper()
dpb = build_dpb(user, password, sql_dialect, role, charset, buffers,force_write,
no_reserve, db_key_scope, no_gc, no_db_triggers, no_linger)
_isc_status = ISC_STATUS_ARRAY()
_db_handle = isc_db_handle(0)
api.isc_attach_database(_isc_status, len(dsn), dsn, _db_handle, len(dpb),
dpb)
if db_api_error(_isc_status):
raise exception_from_status(DatabaseError, _isc_status,
"Error while connecting to database:")
return connection_class(_db_handle, dpb, sql_dialect, charset, isolation_level)
def create_database(sql='', sql_dialect=3, dsn='', user=None, password=None,
host=None, port=3050, database=None,
page_size=None, length=None, charset=None, files=None,
connection_class=None, fb_library_name=None):
"""
Creates a new database. Parameters could be specified either by supplied
"CREATE DATABASE" statement, or set of database parameters.
:param sql: "CREATE DATABASE" statement.
:param sql_dialect: SQL Dialect for newly created database.
:type sql_dialect: 1 or 3
:param dsn: Connection string in format [host[/port]]:database
:param string user: User name. If not specified, fdb attempts to use ISC_USER envar.
:param string password: User password. If not specified, fdb attempts to use ISC_PASSWORD envar.
:param string host: Server host machine specification.
:param integer port: Port used by Firebird server **(not used)**.
:param string database: Database specification (file spec. or alias)
:param integer page_size: Database page size.
:param integer length: Database size in pages.
:param string charset: Character set for connection.
:param string files: Specification of secondary database files.
:param connection_class: Custom connection class
:type connection_class: subclass of :class:`Connection`
:param string fb_library_name: Full path to Firebird client library. See :func:`~fdb.load_api` for details.
:returns: Connection to the newly created database.
:rtype: :class:`Connection` instance.
:raises ProgrammingError: For bad parameter values.
:raises DatabaseError: When database creation fails.
Example:
.. code-block:: python
con = fdb.create_database("create database '/temp/db.fdb' user 'sysdba' password 'pass'")
con = fdb.create_database(dsn='/temp/db.fdb',user='sysdba',password='pass',page_size=8192)
"""
load_api(fb_library_name)
if connection_class == None:
connection_class = Connection
if not issubclass(connection_class,Connection):
raise ProgrammingError("'connection_class' must be subclass of Connection")
# Database to create must be specified by either `sql` or other parameters.
if sql:
if isinstance(sql, myunicode):
sql = sql.encode(_FS_ENCODING)
else:
if not user:
user = os.environ.get('ISC_USER', None)
if not password:
password = os.environ.get('ISC_PASSWORD', None)
if sql_dialect not in [1, 2, 3]:
raise ProgrammingError("SQl Dialect must be either 1, 2 or 3")
if ((not dsn and not host and not database)
or (dsn and (host or database))
or (host and not database)
):
raise ProgrammingError(
"Must supply one of:\n"
" 1. keyword argument dsn='host:/path/to/database'\n"
" 2. both keyword arguments host='host' and"
" database='/path/to/database'\n"
" 3. only keyword argument database='/path/to/database'"
)
if not dsn:
if host and host.endswith(':'):
raise ProgrammingError("Host must not end with a colon."
" You should specify host='%s' rather than host='%s'."
% (host[:-1], host)
)
elif host:
dsn = '%s:%s' % (host, database)
else:
dsn = database
dsn = b(dsn,_FS_ENCODING)
# Parameter checks
sql = "create database '%s' user '%s' password '%s'" % (dsn,user,password)
if page_size:
sql = '%s page_size %i' % (sql,page_size)
if length:
sql = '%s length %i' % (sql,length)
if charset:
sql = '%s default character set %s' % (sql,charset.upper())
if files:
sql = '%s %s' % (sql,files)
isc_status = ISC_STATUS_ARRAY(0)
trans_handle = isc_tr_handle(0)
db_handle = isc_db_handle(0)
xsqlda = xsqlda_factory(1)
# For yet unknown reason, the isc_dsql_execute_immediate segfaults when
# NULL (None) is passed as XSQLDA, so we provide one here
api.isc_dsql_execute_immediate(isc_status, db_handle, trans_handle,
ctypes.c_ushort(len(sql)), sql, sql_dialect,
ctypes.cast(ctypes.pointer(xsqlda),XSQLDA_PTR))
if db_api_error(isc_status):
raise exception_from_status(DatabaseError, isc_status,
"Error while creating database:")
return connection_class(db_handle,sql_dialect=sql_dialect, charset=charset)
class _cursor_weakref_callback(object):
"""Wraps callback function used in weakrefs so it's called only if still exists.
"""
def __init__(self, obj):
self.__obj = weakref.ref(obj)
def __call__(self, *args, **kwargs):
self.__obj()._cursors.remove(*args, **kwargs)
class _weakref_callback(object):
"""Wraps callback function used in weakrefs so it's called only if still exists.
"""
def __init__(self, func):
self.__funcref = weakref.ref(func)
def __call__(self, *args, **kwargs):
func = self.__funcref()
if func:
func(*args, **kwargs)
class TransactionContext(object):
"""Context Manager that manages transaction for object passed to constructor.
Performs `rollback` if exception is thrown inside code block, otherwise
performs `commit` at the end of block.
.. note: :class:`~fdb.Transaction` acts as context manager and supports `with` statement directly.
Example::
with TransactionContext(my_transaction):
cursor.execute('insert into tableA (x,y) values (?,?)',(x,y))
cursor.execute('insert into tableB (x,y) values (?,?)',(x,y))
"""
#: Transaction-like object this instance manages.
transaction = None
def __init__(self,transaction):
":param transaction: Any object that supports `begin()`, `commit()` and `rollback()`."
self.transaction = transaction
def __enter__(self):
self.transaction.begin()
return self.transaction
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type == None:
self.transaction.commit()
else:
self.transaction.rollback()
class Connection(object):
"""
Represents a connection between the database client (the Python process)
and the database server.
.. important::
DO NOT create instances of this class directly! Use only
:func:`connect` or :func:`create_database` to get Connection instances.
"""
# PEP 249 (Python DB API 2.0) extensions
Warning = Warning
Error = Error
InterfaceError = InterfaceError
DatabaseError = DatabaseError
DataError = DataError
OperationalError = OperationalError
IntegrityError = IntegrityError
InternalError = InternalError
ProgrammingError = ProgrammingError
NotSupportedError = NotSupportedError
def __init__(self, db_handle, dpb=None, sql_dialect=3, charset=None,
isolation_level=ISOLATION_LEVEL_READ_COMMITED):
"""
:param db_handle: Database handle provided by factory function.
:param dpb: Database Parameter Block associated with database handle.
:param integer sql_dialect: SQL Dialect associated with database handle.
:param string charset: Character set associated with database handle.
"""
if charset:
self.__charset = charset.upper()
else:
self.__charset = None
self._python_charset = charset_map.get(self.charset, self.charset)
self._default_tpb = isolation_level
# Main transaction
self._main_transaction = Transaction([self], default_tpb=self._default_tpb)
# ReadOnly ReadCommitted transaction
self._query_transaction = Transaction([self],
default_tpb=ISOLATION_LEVEL_READ_COMMITED_RO)
self._transactions = [self._main_transaction,self._query_transaction]
self.__precision_cache = {}
self.__sqlsubtype_cache = {}
self.__conduits = []
self.__group = None
self.__schema = None
self.__monitor = None
self.__ods = None
self.__sql_dialect = sql_dialect
self._dpb = dpb
self._isc_status = ISC_STATUS_ARRAY()
self._db_handle = db_handle
# Cursor for internal use
self.__ic = self.query_transaction.cursor()
self.__ic._set_as_internal()
# Get Firebird engine version
verstr = self.db_info(isc_info_firebird_version)
x = verstr.split()
if x[0].find('V') > 0:
(x,self.__version) = x[0].split('V')
elif x[0].find('T') > 0:
(x,self.__version) = x[0].split('T')
else:
# Unknown version
self.__version = '0.0.0.0'
x = self.__version.split('.')
self.__engine_version = float('%s.%s' % (x[0],x[1]))
#
self.__page_size = self.db_info(isc_info_page_size)
def __remove_group(self, group_ref):
self.__group = None
def __ensure_group_membership(self, must_be_member, err_msg):
if must_be_member:
if self.group is None:
raise ProgrammingError(err_msg)
else:
if self.group is not None:
raise ProgrammingError(err_msg)
def __check_attached(self):
if self._db_handle == None:
raise ProgrammingError("Connection object is detached from database")
def __close(self, detach=True):
if self._db_handle != None:
if self.__schema:
self.__schema._close()
if self.__monitor:
self.__monitor._close()
self.__ic.close()
del self.__ic
try:
for conduit in self.__conduits:
conduit.close()
for transaction in self._transactions:
transaction.default_action = 'rollback' # Required by Python DB API 2.0
transaction.close()
if detach:
api.isc_detach_database(self._isc_status, self._db_handle)
finally:
self._db_handle = None
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def __get_sql_dialect(self):
return self.__sql_dialect
def __get_main_transaction(self):
return self._main_transaction