-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathcore.py
More file actions
5915 lines (5613 loc) · 268 KB
/
core.py
File metadata and controls
5915 lines (5613 loc) · 268 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
# SPDX-FileCopyrightText: 2020-present The Firebird Projects <www.firebirdsql.org>
#
# SPDX-License-Identifier: MIT
#
# PROGRAM/MODULE: firebird-driver
# FILE: firebird/driver/core.py
# DESCRIPTION: Main driver code (connection, transaction, cursor etc.)
# CREATED: 25.3.2020
#
# The contents of this file are subject to the MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Copyright (c) 2020 Firebird Project (www.firebirdsql.org)
# All Rights Reserved.
#
# Contributor(s): Pavel Císař (original code)
# ______________________________________
"""firebird-driver - Main driver code
This module implements the core components of the firebird-driver, including the DB-API 2.0
compliant Connection, Cursor, and Transaction objects, as well as helper classes for managing
events, BLOBs, parameter buffers, and accessing database/server information.
"""
from __future__ import annotations
import atexit
import contextlib
import datetime
import decimal
import io
import itertools
import os
import struct
import sys
import threading
import weakref
from urllib.parse import urlparse
from abc import ABC, abstractmethod
from collections.abc import Callable, Mapping, Sequence
from ctypes import addressof, byref, create_string_buffer, memmove, memset, pointer, string_at
from pathlib import Path
from queue import PriorityQueue
from typing import Any, BinaryIO, Self
from warnings import warn
from firebird.base.buffer import BufferFactory, BytesBufferFactory, CTypesBufferFactory, MemoryBuffer, safe_ord
from firebird.base.types import UNDEFINED, UNLIMITED, ByteOrder, Sentinel
from . import fbapi as a
from .config import DatabaseConfig, driver_config
from .hooks import APIHook, ConnectionHook, ServerHook, add_hook, get_callbacks, register_class
from .interfaces import (
iAttachment,
iBlob,
iCryptKeyCallbackImpl,
iDtc,
iMaster,
iMessageMetadata,
iResultSet,
iService,
iStatement,
iTransaction,
iUtil,
)
from .types import (
CB_OUTPUT_LINE,
DESCRIPTION,
FILESPEC,
BlobInfoCode,
BlobType,
BPBItem,
ConnectionFlag,
CursorFlag,
DatabaseError,
DataError,
DbAccessMode,
DbClass,
DbInfoCode,
DBKeyScope,
DbProvider,
DbSpaceReservation,
DbWriteMode,
DecfloatRound,
DecfloatTraps,
DefaultAction,
DPBItem,
EncryptionFlag,
Error,
Features,
ImpCompiler,
ImpCPU,
ImpData,
ImpDataOld,
ImpFlags,
Implementation,
ImpOS,
IntegrityError,
InterfaceError,
InternalError,
Isolation,
ItemMetadata,
NetProtocol,
NotSupportedError,
OnlineMode,
OperationalError,
ProgrammingError,
ReplicaMode,
ReqInfoCode,
ServerAction,
ServerCapability,
ShutdownMethod,
ShutdownMode,
SPBItem,
SQLDataType,
SrvBackupFlag,
SrvBackupOption,
SrvDbInfoOption,
SrvInfoCode,
SrvNBackupFlag,
SrvNBackupOption,
SrvPropertiesFlag,
SrvPropertiesOption,
SrvRepairFlag,
SrvRepairOption,
SrvRestoreFlag,
SrvRestoreOption,
SrvStatFlag,
SrvTraceOption,
SrvUserOption,
SrvValidateOption,
StatementFlag,
StatementType,
StateResult,
StmtInfoCode,
TableAccessMode,
TableAccessStats,
TableShareMode,
TPBItem,
TraAccessMode,
TraceSession,
TraInfoAccess,
TraInfoCode,
TraIsolation,
TraLockResolution,
Transactional,
TraReadCommitted,
UserInfo,
XpbKind,
)
SHRT_MIN = -32768
SHRT_MAX = 32767
USHRT_MAX = 65535
INT_MIN = -2147483648
INT_MAX = 2147483647
UINT_MAX = 4294967295
LONG_MIN = -9223372036854775808
LONG_MAX = 9223372036854775807
FB50: float = 5.0
FB40: float = 4.0
INFINITE_TIMEOUT: int = -1
#: Max BLOB segment size
MAX_BLOB_SEGMENT_SIZE = 65535
#: Current filesystem encoding
FS_ENCODING = sys.getfilesystemencoding()
#: Python dictionary that maps Firebird character set names (key) to Python character sets (value).
CHARSET_MAP = {None: a.getpreferredencoding(), 'NONE': a.getpreferredencoding(),
'OCTETS': None, 'UNICODE_FSS': 'utf_8', 'UTF8': 'utf_8', 'UTF-8': 'utf_8',
'ASCII': 'ascii', 'SJIS_0208': 'shift_jis', 'EUCJ_0208': 'euc_jp',
'DOS737': 'cp737', 'DOS437': 'cp437', 'DOS850': 'cp850',
'DOS865': 'cp865', 'DOS860': 'cp860', 'DOS863': 'cp863',
'DOS775': 'cp775', 'DOS862': 'cp862', 'DOS864': 'cp864',
'ISO8859_1': 'iso8859_1', 'ISO8859_2': 'iso8859_2',
'ISO8859_3': 'iso8859_3', 'ISO8859_4': 'iso8859_4',
'ISO8859_5': 'iso8859_5', 'ISO8859_6': 'iso8859_6',
'ISO8859_7': 'iso8859_7', 'ISO8859_8': 'iso8859_8',
'ISO8859_9': 'iso8859_9', 'ISO8859_13': 'iso8859_13',
'KSC_5601': 'euc_kr', 'DOS852': 'cp852', 'DOS857': 'cp857',
'DOS858': 'cp858', 'DOS861': 'cp861', 'DOS866': 'cp866',
'DOS869': 'cp869', 'WIN1250': 'cp1250', 'WIN1251': 'cp1251',
'WIN1252': 'cp1252', 'WIN1253': 'cp1253', 'WIN1254': 'cp1254',
'BIG_5': 'big5', 'GB_2312': 'gb2312', 'WIN1255': 'cp1255',
'WIN1256': 'cp1256', 'WIN1257': 'cp1257', 'GB18030': 'gb18030',
'GBK': 'gbk', 'KOI8R': 'koi8_r', 'KOI8U': 'koi8_u',
'WIN1258': 'cp1258',
}
#: Sentinel that denotes timeout expiration
TIMEOUT: Sentinel = Sentinel('TIMEOUT')
# Internal
#: Firebird `.iMaster` interface
_master: iMaster = None
#: Firebird `.iUtil` interface
_util: iUtil = None
_thns = threading.local()
_ten_to = [10 ** x for x in range(30)]
_i2name = {DbInfoCode.READ_SEQ_COUNT: 'sequential', DbInfoCode.READ_IDX_COUNT: 'indexed',
DbInfoCode.INSERT_COUNT: 'inserts', DbInfoCode.UPDATE_COUNT: 'updates',
DbInfoCode.DELETE_COUNT: 'deletes', DbInfoCode.BACKOUT_COUNT: 'backouts',
DbInfoCode.PURGE_COUNT: 'purges', DbInfoCode.EXPUNGE_COUNT: 'expunges'}
_bpb_stream = bytes([1, BPBItem.TYPE, 1, BlobType.STREAM])
# Info structural codes
isc_info_end = 1
isc_info_truncated = 2
isc_info_error = 3
isc_info_data_not_ready = 4
def __api_loaded(api: a.FirebirdAPI) -> None:
setattr(sys.modules[__name__], '_master', api.fb_get_master_interface()) # noqa: B010
setattr(sys.modules[__name__], '_util', _master.get_util_interface()) # noqa: B010
add_hook(APIHook.LOADED, a.FirebirdAPI, __api_loaded)
@atexit.register
def _api_shutdown():
"""Calls a smart shutdown of various Firebird subsystems (yValve, engine, redirector).
"""
if _master is not None:
with _master.get_dispatcher() as provider:
provider.shutdown(0, -3) # fb_shutrsn_app_stopped
def _create_blob_buffer(size: int=MAX_BLOB_SEGMENT_SIZE) -> Any:
if size < MAX_BLOB_SEGMENT_SIZE:
result = getattr(_thns, 'blob_buf', None)
if result is None:
result = create_string_buffer(MAX_BLOB_SEGMENT_SIZE)
_thns.blob_buf = result
else:
memset(result, 0, MAX_BLOB_SEGMENT_SIZE)
else:
result = create_string_buffer(size)
return result
def _encode_timestamp(v: datetime.datetime | datetime.date) -> bytes:
# Convert datetime.datetime or datetime.date to BLR format timestamp
if isinstance(v, datetime.datetime):
return _util.encode_date(v.date()).to_bytes(4, 'little') + _util.encode_time(v.time()).to_bytes(4, 'little')
if isinstance(v, datetime.date):
return _util.encode_date(v).to_bytes(4, 'little') + _util.encode_time(datetime.time()).to_bytes(4, 'little')
raise ValueError("datetime.datetime or datetime.date expected")
def _is_fixed_point(dialect: int, datatype: SQLDataType, subtype: int,
scale: int) -> bool:
return ((datatype in (SQLDataType.SHORT, SQLDataType.LONG, SQLDataType.INT64)
and (subtype or scale))
or
((dialect < 3) and scale
and (datatype in (SQLDataType.DOUBLE, SQLDataType.D_FLOAT)))
)
def _get_external_data_type_name(dialect: int, datatype: SQLDataType,
subtype: int, scale: int) -> str:
if _is_fixed_point(dialect, datatype, subtype, scale):
return {1: 'NUMERIC', 2: 'DECIMAL'}.get(subtype, 'NUMERIC/DECIMAL')
return {SQLDataType.TEXT: 'CHAR', SQLDataType.VARYING: 'VARCHAR',
SQLDataType.SHORT: 'SMALLINT', SQLDataType.LONG: 'INTEGER',
SQLDataType.INT64: 'BIGINT', SQLDataType.FLOAT: 'FLOAT',
SQLDataType.DOUBLE: 'DOUBLE', SQLDataType.D_FLOAT: 'DOUBLE',
SQLDataType.TIMESTAMP: 'TIMESTAMP', SQLDataType.DATE: 'DATE',
SQLDataType.TIME: 'TIME', SQLDataType.BLOB: 'BLOB',
SQLDataType.BOOLEAN: 'BOOLEAN'}.get(datatype, 'UNKNOWN')
def _get_internal_data_type_name(data_type: SQLDataType) -> str:
if data_type in (SQLDataType.DOUBLE, SQLDataType.D_FLOAT):
value = SQLDataType.DOUBLE
else:
value = data_type
return value.name
def _check_integer_range(value: int, dialect: int, datatype: SQLDataType,
subtype: int, scale: int) -> None:
if datatype == SQLDataType.SHORT:
vmin = SHRT_MIN
vmax = SHRT_MAX
elif datatype == SQLDataType.LONG:
vmin = INT_MIN
vmax = INT_MAX
elif datatype == SQLDataType.INT64:
vmin = LONG_MIN
vmax = LONG_MAX
if (value < vmin) or (value > vmax):
msg = f"""numeric overflow: value {value}
({_get_external_data_type_name(dialect, datatype, subtype, scale)} scaled for {scale} decimal places) is of
too great a magnitude to fit into its internal storage type {_get_internal_data_type_name(datatype)},
which has range [{vmin},{vmax}]."""
raise ValueError(msg)
def _is_str_param(value: Any, datatype: SQLDataType) -> bool:
return ((isinstance(value, str) and datatype != SQLDataType.BLOB) or
datatype in (SQLDataType.TEXT, SQLDataType.VARYING))
def create_meta_descriptors(meta: iMessageMetadata) -> list[ItemMetadata]:
"Returns list of metadata descriptors from statement metadata."
result = []
for i in range(meta.get_count()):
result.append(ItemMetadata(field=meta.get_field(i),
relation=meta.get_relation(i),
owner=meta.get_owner(i),
alias=meta.get_alias(i),
datatype=meta.get_type(i),
nullable=meta.is_nullable(i),
subtype=meta.get_subtype(i),
length=meta.get_length(i),
scale=meta.get_scale(i),
charset=meta.get_charset(i),
offset=meta.get_offset(i),
null_offset=meta.get_null_offset(i)
))
return result
# Context managers
@contextlib.contextmanager
def transaction(transact_object: Transactional, *, tpb: bytes | None=None, bypass: bool=False) -> Transactional:
"""Context manager for `~firebird.driver.types.Transactional` objects.
Starts new transaction when context is entered. On exit calls `rollback()` when
exception was raised, or `commit()` if there was no error. Exception raised
in managed context is NOT suppressed.
Arguments:
transact_object: Managed transactional object.
tpb: Transaction parameter buffer used to start the transaction.
bypass: When both `bypass` and `transact_object.is_active()` are `True` when
context is entered, the context manager does nothing on exit.
"""
if bypass and transact_object.is_active():
yield transact_object
else:
try:
transact_object.begin(tpb)
yield transact_object
except:
transact_object.rollback()
raise
else:
transact_object.commit()
@contextlib.contextmanager
def temp_database(*args, **kwargs) -> Connection:
"""Context manager for temporary databases. Creates new database when context
is entered, and drops it on exit. Exception raised in managed context is NOT suppressed.
All positional and keyword arguments are passed to `create_database`.
"""
con = create_database(*args, **kwargs)
try:
yield con
except:
con.drop_database()
raise
else:
con.drop_database()
_OP_DIE = object()
_OP_RECORD_AND_REREGISTER = object()
# Managers for Parameter buffers
class TPB:
"""Helper class to build and parse Transaction Parameter Buffers (TPB) used when starting transactions.
"""
def __init__(self, *, access_mode: TraAccessMode=TraAccessMode.WRITE,
isolation: Isolation=Isolation.SNAPSHOT,
lock_timeout: int=INFINITE_TIMEOUT,
no_auto_undo: bool=False,
auto_commit: bool=False,
ignore_limbo: bool=False,
at_snapshot_number: int | None=None,
encoding: str='ascii'):
self.encoding: str = encoding
self.access_mode: TraAccessMode = access_mode
self.isolation: Isolation = isolation
self.lock_timeout: int = lock_timeout
self.no_auto_undo: bool = no_auto_undo
self.auto_commit: bool = auto_commit
self.ignore_limbo: bool = ignore_limbo
self._table_reservation: list[tuple[str, TableShareMode, TableAccessMode]] = []
# Firebird 4
self.at_snapshot_number: int | None = at_snapshot_number
def clear(self) -> None:
"""Clear all information.
"""
self.access_mode = TraAccessMode.WRITE
self.isolation = Isolation.SNAPSHOT
self.lock_timeout = -1
self.no_auto_undo = False
self.auto_commit = False
self.ignore_limbo = False
self._table_reservation = []
# Firebird 4
self.at_snapshot_number = None
def parse_buffer(self, buffer: bytes) -> None:
"""Load information from TPB.
"""
self.clear()
with a.get_api().util.get_xpb_builder(XpbKind.TPB, buffer) as tpb:
while not tpb.is_eof():
tag = tpb.get_tag()
if tag in TraAccessMode._value2member_map_:
self.access_mode = TraAccessMode(tag)
elif tag in TraIsolation._value2member_map_:
isolation = TraIsolation(tag)
if isolation != TraIsolation.READ_COMMITTED:
self.isolation = Isolation(isolation)
elif tag in TraReadCommitted._value2member_map_:
isolation = TraReadCommitted(tag)
if isolation == TraReadCommitted.RECORD_VERSION:
self.isolation = Isolation.READ_COMMITTED_RECORD_VERSION
elif isolation == TraReadCommitted.NO_RECORD_VERSION:
self.isolation = Isolation.READ_COMMITTED_NO_RECORD_VERSION
else:
self.isolation = Isolation.READ_COMMITTED_READ_CONSISTENCY
elif tag in TraLockResolution._value2member_map_:
self.lock_timeout = -1 if TraLockResolution(tag) is TraLockResolution.WAIT else 0
elif tag == TPBItem.AUTOCOMMIT:
self.auto_commit = True
elif tag == TPBItem.NO_AUTO_UNDO:
self.no_auto_undo = True
elif tag == TPBItem.IGNORE_LIMBO:
self.ignore_limbo = True
elif tag == TPBItem.LOCK_TIMEOUT:
self.lock_timeout = tpb.get_int()
elif tag == TPBItem.AT_SNAPSHOT_NUMBER:
self.at_snapshot_number = tpb.get_bigint()
elif tag in TableAccessMode._value2member_map_:
tbl_access = TableAccessMode(tag)
tbl_name = tpb.get_string(encoding=self.encoding)
tpb.move_next()
if tpb.is_eof():
raise ValueError(f"Missing share mode value in table {tbl_name} reservation")
if (val := tpb.get_tag()) not in TableShareMode._value2member_map_:
raise ValueError(f"Missing share mode value in table {tbl_name} reservation")
tbl_share = TableShareMode(val)
self.reserve_table(tbl_name, tbl_share, tbl_access)
tpb.move_next()
def get_buffer(self) -> bytes:
"""Create TPB from stored information.
"""
with a.get_api().util.get_xpb_builder(XpbKind.TPB) as tpb:
tpb.insert_tag(self.access_mode)
isolation = (Isolation.READ_COMMITTED_RECORD_VERSION
if self.isolation == Isolation.READ_COMMITTED
else self.isolation)
if isolation in (Isolation.SNAPSHOT, Isolation.SERIALIZABLE):
tpb.insert_tag(isolation)
elif isolation == Isolation.READ_COMMITTED_READ_CONSISTENCY:
tpb.insert_tag(TPBItem.READ_CONSISTENCY)
else:
tpb.insert_tag(TraIsolation.READ_COMMITTED)
tpb.insert_tag(TraReadCommitted.RECORD_VERSION
if isolation == Isolation.READ_COMMITTED_RECORD_VERSION
else TraReadCommitted.NO_RECORD_VERSION)
tpb.insert_tag(TraLockResolution.NO_WAIT if self.lock_timeout == 0 else TraLockResolution.WAIT)
if self.lock_timeout > 0:
tpb.insert_int(TPBItem.LOCK_TIMEOUT, self.lock_timeout)
if self.auto_commit:
tpb.insert_tag(TPBItem.AUTOCOMMIT)
if self.no_auto_undo:
tpb.insert_tag(TPBItem.NO_AUTO_UNDO)
if self.ignore_limbo:
tpb.insert_tag(TPBItem.IGNORE_LIMBO)
if self.at_snapshot_number is not None:
tpb.insert_bigint(TPBItem.AT_SNAPSHOT_NUMBER, self.at_snapshot_number)
for table in self._table_reservation:
# Access mode + table name
tpb.insert_string(table[2], table[0], encoding=self.encoding)
tpb.insert_tag(table[1]) # Share mode
result = tpb.get_buffer()
return result
def reserve_table(self, name: str, share_mode: TableShareMode, access_mode: TableAccessMode) -> None:
"""Set information about table reservation.
"""
self._table_reservation.append((name, share_mode, access_mode))
class DPB:
"""Helper class to build and parse Database Parameter Buffers (DPB) used when connecting databases.
"""
def __init__(self, *, user: str | None=None, password: str | None=None, role: str | None=None,
trusted_auth: bool=False, sql_dialect: int=3, timeout: int | None=None,
charset: str='UTF8', cache_size: int | None=None, no_gc: bool=False,
no_db_triggers: bool=False, no_linger: bool=False,
utf8filename: bool=False, dbkey_scope: DBKeyScope | None=None,
dummy_packet_interval: int | None=None, overwrite: bool=False,
db_cache_size: int | None=None, forced_writes: bool | None=None,
reserve_space: bool | None=None, page_size: int | None=None, read_only: bool=False,
sweep_interval: int | None=None, db_sql_dialect: int | None=None,
db_charset: str | None=None, config: str | None=None,
auth_plugin_list: str | None=None, session_time_zone: str | None=None,
set_db_replica: ReplicaMode | None=None, set_bind: str | None=None,
decfloat_round: DecfloatRound | None=None,
decfloat_traps: list[DecfloatTraps] | None=None,
parallel_workers: int | None=None
):
# Available options:
# AuthClient, WireCryptPlugin, Providers, ConnectionTimeout, WireCrypt,
# WireCompression, DummyPacketInterval, RemoteServiceName, RemoteServicePort,
# RemoteAuxPort, TcpNoNagle, IpcName, RemotePipeName, ClientBatchBuffer [FB4+]
#: Configuration override
self.config: str | None = config
#: List of authentication plugins override
self.auth_plugin_list: str | None = auth_plugin_list
# Connect
#: Use trusted authentication
self.trusted_auth: bool = trusted_auth
#: User name
self.user: str | None = user
#: User password
self.password: str | None = password
#: User role
self.role: str | None = role
#: SQL Dialect for database connection
self.sql_dialect: int = sql_dialect
#: Character set for database connection
self.charset: str = charset
#: Connection timeout
self.timeout: int | None = timeout
#: Dummy packet interval for this database connection
self.dummy_packet_interval: int | None = dummy_packet_interval
#: Page cache size override for database connection
self.cache_size: int | None = cache_size
#: Disable garbage collection for database connection
self.no_gc: bool = no_gc
#: Disable database triggers for database connection
self.no_db_triggers: bool = no_db_triggers
#: Do not use linger for database connection
self.no_linger: bool = no_linger
#: Database filename passed in UTF8
self.utf8filename: bool = utf8filename
#: Scope for RDB$DB_KEY values
self.dbkey_scope: DBKeyScope | None = dbkey_scope
#: Session time zone [Firebird 4]
self.session_time_zone: str | None = session_time_zone
#: Set replica mode [Firebird 4]
self.set_db_replica: ReplicaMode | None = set_db_replica
#: Set BIND [Firebird 4]
self.set_bind: str | None = set_bind
#: Set DECFLOAT ROUND [Firebird 4]
self.decfloat_round: DecfloatRound | None = decfloat_round
#: Set DECFLOAT TRAPS [Firebird 4]
self.decfloat_traps: list[DecfloatTraps] | None = \
None if decfloat_traps is None else list(decfloat_traps)
# For db create
#: Database page size [db create only]
self.page_size: int | None = page_size
#: Overwrite existing database [db create only]
self.overwrite: bool = overwrite
#: Number of pages in database cache [db create only]
self.db_buffers: int | None= None
#: Database cache size [db create only]
self.db_cache_size: int | None = db_cache_size
#: Database write mode (True = sync/False = async) [db create only]
self.forced_writes: bool | None = forced_writes
#: Database data page space usage (True = reserve space, False = Use all space) [db create only]
self.reserve_space: bool | None = reserve_space
#: Database access mode (True = read-only/False = read-write) [db create only]
self.read_only: bool = read_only
#: Sweep interval for the database [db create only]
self.sweep_interval: int | None = sweep_interval
#: SQL dialect for the database [db create only]
self.db_sql_dialect: int | None = db_sql_dialect
#: Character set for the database [db create only]
self.db_charset: str | None = db_charset
#: Number of parallel workers
self.parallel_workers: int | None = parallel_workers
def clear(self) -> None:
"""Clear all information.
"""
self.config = None
# Connect
self.trusted_auth = False
self.user = None
self.password = None
self.role = None
self.sql_dialect = 3
self.charset = 'UTF8'
self.timeout = None
self.dummy_packet_interval = None
self.cache_size = None
self.no_gc = False
self.no_db_triggers = False
self.no_linger = False
self.utf8filename = False
self.dbkey_scope = None
self.session_time_zone = None
self.set_db_replica = None
self.set_bind = None
self.decfloat_round = None
self.decfloat_traps = None
# For db create
self.page_size = None
self.overwrite = False
self.db_buffers = None
self.forced_writes = None
self.reserve_space = None
self.page_size = None
self.read_only = False
self.sweep_interval = None
self.db_sql_dialect = None
self.db_charset = None
def parse_buffer(self, buffer: bytes) -> None:
"""Load information from DPB.
"""
_py_charset: str = CHARSET_MAP.get(self.charset, 'ascii')
self.clear()
with a.get_api().util.get_xpb_builder(XpbKind.DPB, buffer) as dpb:
while not dpb.is_eof():
tag = dpb.get_tag()
if tag == DPBItem.CONFIG:
self.config = dpb.get_string(encoding=_py_charset)
elif tag == DPBItem.AUTH_PLUGIN_LIST:
self.auth_plugin_list = dpb.get_string()
elif tag == DPBItem.TRUSTED_AUTH:
self.trusted_auth = True
elif tag == DPBItem.USER_NAME:
self.user = dpb.get_string(encoding=_py_charset)
elif tag == DPBItem.PASSWORD:
self.password = dpb.get_string(encoding=_py_charset)
elif tag == DPBItem.CONNECT_TIMEOUT:
self.timeout = dpb.get_int()
elif tag == DPBItem.DUMMY_PACKET_INTERVAL:
self.dummy_packet_interval = dpb.get_int()
elif tag == DPBItem.SQL_ROLE_NAME:
self.role = dpb.get_string(encoding=_py_charset)
elif tag == DPBItem.SQL_DIALECT:
self.sql_dialect = dpb.get_int()
elif tag == DPBItem.LC_CTYPE:
self.charset = dpb.get_string()
elif tag == DPBItem.NUM_BUFFERS:
self.cache_size = dpb.get_int()
elif tag == DPBItem.NO_GARBAGE_COLLECT:
self.no_gc = bool(dpb.get_int())
elif tag == DPBItem.UTF8_FILENAME:
self.utf8filename = bool(dpb.get_int())
elif tag == DPBItem.NO_DB_TRIGGERS:
self.no_db_triggers = bool(dpb.get_int())
elif tag == DPBItem.NOLINGER:
self.no_linger = bool(dpb.get_int())
elif tag == DPBItem.DBKEY_SCOPE:
self.dbkey_scope = DBKeyScope(dpb.get_int())
elif tag == DPBItem.PAGE_SIZE:
self.page_size = dpb.get_int()
elif tag == DPBItem.OVERWRITE:
self.overwrite = bool(dpb.get_int())
elif tag == DPBItem.SET_PAGE_BUFFERS:
self.db_cache_size = dpb.get_int()
elif tag == DPBItem.FORCE_WRITE:
self.forced_writes = bool(dpb.get_int())
elif tag == DPBItem.NO_RESERVE:
self.reserve_space = not bool(dpb.get_int())
elif tag == DPBItem.SET_DB_READONLY:
self.read_only = bool(dpb.get_int())
elif tag == DPBItem.SWEEP_INTERVAL:
self.sweep_interval = dpb.get_int()
elif tag == DPBItem.SET_DB_SQL_DIALECT:
self.db_sql_dialect = dpb.get_int()
elif tag == DPBItem.SET_DB_CHARSET:
self.db_charset = dpb.get_string()
elif tag == DPBItem.SESSION_TIME_ZONE:
self.session_time_zone = dpb.get_string()
elif tag == DPBItem.SET_DB_REPLICA:
self.set_db_replica = ReplicaMode(dpb.get_int())
elif tag == DPBItem.SET_BIND:
self.set_bind = dpb.get_string()
elif tag == DPBItem.DECFLOAT_ROUND:
self.decfloat_round = DecfloatRound(dpb.get_string())
elif tag == DPBItem.DECFLOAT_TRAPS:
self.decfloat_traps = [DecfloatTraps(v.strip())
for v in dpb.get_string().split(',')]
elif tag == DPBItem.PARALLEL_WORKERS:
self.parallel_workers = dpb.get_int()
dpb.move_next()
def get_buffer(self, *, for_create: bool=False) -> bytes:
"""Create DPB from stored information.
"""
_py_charset: str = CHARSET_MAP.get(self.charset, 'ascii')
with a.get_api().util.get_xpb_builder(XpbKind.DPB) as dpb:
if self.config is not None:
dpb.insert_string(DPBItem.CONFIG, self.config, encoding=_py_charset)
if self.trusted_auth:
dpb.insert_tag(DPBItem.TRUSTED_AUTH)
else:
if self.user:
dpb.insert_string(DPBItem.USER_NAME, self.user, encoding=_py_charset)
if self.password:
dpb.insert_string(DPBItem.PASSWORD, self.password, encoding=_py_charset)
if self.auth_plugin_list is not None:
dpb.insert_string(DPBItem.AUTH_PLUGIN_LIST, self.auth_plugin_list)
if self.timeout is not None:
dpb.insert_int(DPBItem.CONNECT_TIMEOUT, self.timeout)
if self.dummy_packet_interval is not None:
dpb.insert_int(DPBItem.DUMMY_PACKET_INTERVAL, self.dummy_packet_interval)
if self.role:
dpb.insert_string(DPBItem.SQL_ROLE_NAME, self.role, encoding=_py_charset)
if self.sql_dialect:
dpb.insert_int(DPBItem.SQL_DIALECT, self.sql_dialect)
if self.charset:
dpb.insert_string(DPBItem.LC_CTYPE, self.charset)
if for_create:
dpb.insert_string(DPBItem.SET_DB_CHARSET, self.charset)
if self.cache_size is not None:
dpb.insert_int(DPBItem.NUM_BUFFERS, self.cache_size)
if self.no_gc:
dpb.insert_int(DPBItem.NO_GARBAGE_COLLECT, 1)
if self.utf8filename:
dpb.insert_int(DPBItem.UTF8_FILENAME, 1)
if self.no_db_triggers:
dpb.insert_int(DPBItem.NO_DB_TRIGGERS, 1)
if self.no_linger:
dpb.insert_int(DPBItem.NOLINGER, 1)
if self.dbkey_scope is not None:
dpb.insert_int(DPBItem.DBKEY_SCOPE, self.dbkey_scope)
if self.session_time_zone is not None:
dpb.insert_string(DPBItem.SESSION_TIME_ZONE, self.session_time_zone)
if self.set_db_replica is not None:
dpb.insert_int(DPBItem.SET_DB_REPLICA, self.set_db_replica)
if self.set_bind is not None:
dpb.insert_string(DPBItem.SET_BIND, self.set_bind)
if self.decfloat_round is not None:
dpb.insert_string(DPBItem.DECFLOAT_ROUND, self.decfloat_round.value)
if self.decfloat_traps is not None:
dpb.insert_string(DPBItem.DECFLOAT_TRAPS, ','.join(e.value for e in
self.decfloat_traps))
if self.parallel_workers is not None:
dpb.insert_int(DPBItem.PARALLEL_WORKERS, self.parallel_workers)
if for_create:
if self.page_size is not None:
dpb.insert_int(DPBItem.PAGE_SIZE, self.page_size)
if self.overwrite:
dpb.insert_int(DPBItem.OVERWRITE, 1)
if self.db_cache_size is not None:
dpb.insert_int(DPBItem.SET_PAGE_BUFFERS, self.db_cache_size)
if self.forced_writes is not None:
dpb.insert_int(DPBItem.FORCE_WRITE, int(self.forced_writes))
if self.reserve_space is not None:
dpb.insert_int(DPBItem.NO_RESERVE, int(not self.reserve_space))
if self.read_only:
dpb.insert_int(DPBItem.SET_DB_READONLY, 1)
if self.sweep_interval is not None:
dpb.insert_int(DPBItem.SWEEP_INTERVAL, self.sweep_interval)
if self.db_sql_dialect is not None:
dpb.insert_int(DPBItem.SET_DB_SQL_DIALECT, self.db_sql_dialect)
if self.db_charset is not None:
dpb.insert_string(DPBItem.SET_DB_CHARSET, self.db_charset)
#
result = dpb.get_buffer()
return result
class SPB_ATTACH: # noqa: N801
"""Helper class to build and parse Service Parameter Buffers (SPB) used when connecting
to service manager.
"""
def __init__(self, *, user: str | None=None, password: str | None=None, trusted_auth: bool=False,
config: str | None=None, auth_plugin_list: str | None=None, expected_db: str | None=None,
encoding: str='ascii', errors: str='strict', role: str | None=None):
self.encoding: str = encoding
self.errors: str = errors
self.user: str | None = user
self.password: str | None = password
self.trusted_auth: bool = trusted_auth
self.config: str | None = config
self.auth_plugin_list: str | None = auth_plugin_list
self.expected_db: str | None = expected_db
self.role: str | None = role
def clear(self) -> None:
"""Clear all information.
"""
self.user = None
self.password = None
self.trusted_auth = False
self.config = None
self.expected_db = None
def parse_buffer(self, buffer: bytes) -> None:
"""Load information from SPB_ATTACH.
"""
self.clear()
with a.get_api().util.get_xpb_builder(XpbKind.SPB_ATTACH, buffer) as spb:
while not spb.is_eof():
tag = spb.get_tag()
if tag == SPBItem.CONFIG:
self.config = spb.get_string(encoding=self.encoding, errors=self.errors)
elif tag == SPBItem.AUTH_PLUGIN_LIST:
self.auth_plugin_list = spb.get_string()
elif tag == SPBItem.TRUSTED_AUTH:
self.trusted_auth = True
elif tag == SPBItem.USER_NAME:
self.user = spb.get_string(encoding=self.encoding, errors=self.errors)
elif tag == SPBItem.PASSWORD:
self.password = spb.get_string(encoding=self.encoding, errors=self.errors)
elif tag == SPBItem.SQL_ROLE_NAME:
self.role = spb.get_string(encoding=self.encoding, errors=self.errors)
elif tag == SPBItem.EXPECTED_DB:
self.expected_db = spb.get_string(encoding=self.encoding, errors=self.errors)
spb.move_next()
def get_buffer(self) -> bytes:
"""Create SPB_ATTACH from stored information.
"""
with a.get_api().util.get_xpb_builder(XpbKind.SPB_ATTACH) as spb:
if self.config is not None:
spb.insert_string(SPBItem.CONFIG, self.config, encoding=self.encoding,
errors=self.errors)
if self.trusted_auth:
spb.insert_tag(SPBItem.TRUSTED_AUTH)
else:
if self.user is not None:
spb.insert_string(SPBItem.USER_NAME, self.user, encoding=self.encoding,
errors=self.errors)
if self.password is not None:
spb.insert_string(SPBItem.PASSWORD, self.password,
encoding=self.encoding, errors=self.errors)
if self.role is not None:
spb.insert_string(SPBItem.SQL_ROLE_NAME, self.role, encoding=self.encoding,
errors=self.errors)
if self.auth_plugin_list is not None:
spb.insert_string(SPBItem.AUTH_PLUGIN_LIST, self.auth_plugin_list)
if self.expected_db is not None:
spb.insert_string(SPBItem.EXPECTED_DB, self.expected_db,
encoding=self.encoding, errors=self.errors)
result = spb.get_buffer()
return result
class Buffer(MemoryBuffer):
"""MemoryBuffer with extensions.
"""
def __init__(self, init: int | bytes, size: int | None=None, *,
factory: type[BufferFactory]=BytesBufferFactory,
max_size: int | UNLIMITED=UNLIMITED, byteorder: ByteOrder=ByteOrder.LITTLE):
super().__init__(init, size, factory=factory, eof_marker=isc_info_end,
max_size=max_size, byteorder=byteorder)
def seek_last_data(self) -> int:
"""Set the position in buffer to first non-zero byte when searched from
the end of buffer.
"""
self.pos = self.last_data
def get_tag(self) -> int:
"""Read 1 byte number (c_ubyte).
"""
return self.read_byte()
def rewind(self) -> None:
"""Set current position in buffer to beginning.
"""
self.pos = 0
def is_truncated(self) -> bool:
"""Return True when positioned on `isc_info_truncated` tag.
"""
return safe_ord(self.raw[self.pos]) == isc_info_truncated
class CBuffer(Buffer):
"""ctypes MemoryBuffer with extensions.
"""
def __init__(self, init: int | bytes, size: int | None=None, *,
max_size: int | UNLIMITED=UNLIMITED, byteorder: ByteOrder=ByteOrder.LITTLE):
super().__init__(init, size, factory=CTypesBufferFactory, max_size=max_size, byteorder=byteorder)
class EventBlock:
"""Used internally by `EventCollector`.
"""
def __init__(self, queue, db_handle: a.FB_API_HANDLE, event_names: list[str]):
self.__first = True
def callback(result, length, updated):
memmove(result, updated, length)
self.__queue.put((_OP_RECORD_AND_REREGISTER, self))
return 0
self.__queue: PriorityQueue = weakref.proxy(queue)
self._db_handle: a.FB_API_HANDLE = db_handle
self._isc_status: a.ISC_STATUS_ARRAY = a.ISC_STATUS_ARRAY(0)
self.event_names: list[str] = event_names
self.__results: a.RESULT_VECTOR = a.RESULT_VECTOR(0)
self.__closed: bool = False
self.__callback: a.ISC_EVENT_CALLBACK = a.ISC_EVENT_CALLBACK(callback)
self.event_buf = pointer(a.ISC_UCHAR(0))
self.result_buf = pointer(a.ISC_UCHAR(0))
self.buf_length: int = 0
self.event_id: a.ISC_LONG = a.ISC_LONG(0)
self.buf_length = a.api.isc_event_block(pointer(self.event_buf),
pointer(self.result_buf),
*[x.encode() for x in event_names])
def __del__(self):
if not self.__closed:
warn("EventBlock disposed without prior close()", ResourceWarning)
self.close()
def __lt__(self, other):
return self.event_id.value < other.event_id.value
def __wait_for_events(self) -> None:
a.api.isc_que_events(self._isc_status, self._db_handle, self.event_id,
self.buf_length, self.event_buf,
self.__callback, self.result_buf)
if a.db_api_error(self._isc_status): # pragma: no cover
self.close()
raise a.exception_from_status(DatabaseError, self._isc_status,
"Error while waiting for events.")
def _begin(self) -> None:
self.__wait_for_events()
def count_and_reregister(self) -> dict[str, int]:
"""Count event occurences and re-register interest in further notifications.
"""
result = {}
a.api.isc_event_counts(self.__results, self.buf_length,
self.event_buf, self.result_buf)
if self.__first:
# Ignore the first call, it's for setting up the table
self.__first = False
self.__wait_for_events()
return None
for i, name in enumerate(self.event_names):
result[name] = int(self.__results[i])
self.__wait_for_events()
return result
def close(self) -> None:
"""Close this block canceling managed events.
"""
if not self.__closed:
a.api.isc_cancel_events(self._isc_status, self._db_handle, self.event_id)
self.__closed = True
del self.__callback
if a.db_api_error(self._isc_status): # pragma: no cover
raise a.exception_from_status(DatabaseError, self._isc_status,
"Error while canceling events.")
def is_closed(self) -> bool:
"""Returns True if event block is closed.
"""
return self.__closed
class EventCollector:
"""Collects database event notifications.
Notifications of events are not accumulated until `.begin()` method is called.
From the moment the `.begin()` is called, notifications of any events that occur
will accumulate asynchronously within the conduit's internal queue until the collector
is closed either explicitly (via the `.close()` method) or implicitly
(via garbage collection).
Note:
`EventCollector` implements context manager protocol to call method `.begin()`
and `.close()` automatically.
Example::
with connection.event_collector(['event_a', 'event_b']) as collector:
events = collector.wait()
process_events(events)
Important:
DO NOT create instances of this class directly! Use only
`Connection.event_collector` to get EventCollector instances.
"""
def __init__(self, db_handle: a.FB_API_HANDLE, event_names: Sequence[str]):
self._db_handle: a.FB_API_HANDLE = db_handle
self._isc_status: a.ISC_STATUS_ARRAY = a.ISC_STATUS_ARRAY(0)
self.__event_names: list[str] = list(event_names)
self.__events: dict[str, int] = dict.fromkeys(self.__event_names, 0)
self.__event_blocks: list[EventBlock] = []
self.__closed: bool = False
self.__queue: PriorityQueue = PriorityQueue()
self.__events_ready: threading.Event = threading.Event()
self.__blocks: list[list[str]] = [[x for x in y if x] for y in itertools.zip_longest(*[iter(event_names)]*15)]
self.__initialized: bool = False
self.__process_thread = None
def __del__(self) -> None:
if not self.__closed:
warn("EventCollector disposed without prior close()", ResourceWarning)
self.close()
def __enter__(self) -> Self:
self.begin()