-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathinterfaces.py
More file actions
2024 lines (1949 loc) · 90.2 KB
/
interfaces.py
File metadata and controls
2024 lines (1949 loc) · 90.2 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/interfaces.py
# DESCRIPTION: Interface wrappers for Firebird new API
# CREATED: 11.6.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 - Interface wrappers for Firebird new API
"""
from __future__ import annotations
import datetime
import sys
import threading
from collections.abc import ByteString
from contextlib import suppress
from ctypes import (
byref,
c_byte,
c_char_p,
c_ulong,
c_void_p,
cast,
create_string_buffer,
memmove,
memset,
sizeof,
string_at,
)
from typing import Any
from warnings import warn
from . import fbapi as a
from .hooks import APIHook, add_hook
from .types import (
BCD,
BlobInfoCode,
CursorFlag,
DatabaseError,
DirectoryCode,
Error,
FirebirdWarning,
InterfaceError,
PreparePrefetchFlag,
SQLDataType,
StateFlag,
StatementFlag,
StatementType,
StateResult,
XpbKind,
get_timezone,
)
# Internal
_master = None
_util = None
_thns = threading.local()
# Info structural codes
isc_info_end = 1
# ------------------------------------------------------------------------------
# Interface wrappers
# ------------------------------------------------------------------------------
class iVersionedMeta(type):
"""Metaclass for iVersioned interfaces.
This metaclass uses MRO to instantiate wrapper interface with version that matches version
of wrapped interface.
"""
def __call__(cls: iVersioned, intf):
v = intf.contents.vtable.contents.version
for c in cls.__mro__:
if getattr(c, 'VERSION', 0) <= v:
result = super(iVersionedMeta, iVersionedMeta).__call__(c, intf)
#print(f"{result.__class__.__name__}.{getattr(c, 'VERSION', 0)}")
return result
#return super(iVersionedMeta, iVersionedMeta).__call__(c, intf)
return None
# IVersioned(1)
class iVersioned(metaclass=iVersionedMeta):
"IVersioned interface wrapper"
VERSION = 1
def __init__(self, intf):
self._as_parameter_ = intf
if intf and self.vtable.version < self.VERSION: # pragma: no cover
raise InterfaceError(f"Wrong interface version {self.vtable.version}, expected {self.VERSION}")
def __report(self, cls: Error | FirebirdWarning, vector_ptr: a.ISC_STATUS_ARRAY_PTR) -> None:
msg = _util.format_status(self.status)
sqlstate = create_string_buffer(6)
a.api.fb_sqlstate(sqlstate, vector_ptr)
i = 0
gds_codes = []
sqlcode = a.api.isc_sqlcode(vector_ptr)
while vector_ptr[i] != 0:
if vector_ptr[i] == 1:
i += 1
if (vector_ptr[i] & 0x14000000) == 0x14000000: # noqa: PLR2004
gds_codes.append(vector_ptr[i])
if (vector_ptr[i] == 335544436) and (vector_ptr[i + 1] == 4): # noqa: PLR2004
i += 2
sqlcode = vector_ptr[i]
i += 1
# We need to clean up the iStatus before returning
self.status.init()
return cls(msg, sqlstate=sqlstate.value.decode(),
gds_codes=tuple(gds_codes), sqlcode=sqlcode,)
def _check(self) -> None:
state = self.status.get_state()
if StateFlag.ERRORS in state:
raise self.__report(DatabaseError, self.status.get_errors())
if StateFlag.WARNINGS in state: # pragma: no cover
#raise self.__report(FirebirdWarning, self.status.get_warning())
warn(self.__report(FirebirdWarning, self.status.get_warning()),
stacklevel=2)
@property
def status(self) -> iStatus:
"iStatus for interface"
if (result := getattr(_thns, 'status', None)) is None:
result = _master.get_status()
_thns.status = result
return result
@property
def vtable(self):
"Interface method table"
return self._as_parameter_.contents.vtable.contents
@property
def version(self) -> int:
"Interface version"
return self._as_parameter_.contents.vtable.contents.version.value
# IReferenceCounted(2)
class iReferenceCounted(iVersioned):
"IReferenceCounted interface wrapper"
VERSION = 2
def __init__(self, intf):
super().__init__(intf)
self._refcnt: int = 1
def __del__(self):
if self._refcnt > 0:
self.release()
def __enter__(self) -> iReferenceCounted:
return self
def __exit__(self, exc_type, exc_value, traceback) -> None:
self.release()
def add_ref(self) -> None:
"Increase the reference by one"
self._refcnt += 1
self.vtable.addRef(cast(self, a.IReferenceCounted))
def release(self) -> int:
"Decrease the reference by one"
self._refcnt -= 1
result = self.vtable.release(cast(self, a.IReferenceCounted))
return result
# IDisposable(2)
class iDisposable(iVersioned):
"IDisposable interface wrapper"
VERSION = 2
def __init__(self, intf):
super().__init__(intf)
self._disposed: bool = False
def __del__(self):
if not self._disposed:
self.dispose()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.dispose()
def dispose(self) -> None:
"Dispose the interfaced object"
if not self._disposed:
self.vtable.dispose(cast(self, a.IDisposable))
self._disposed = True
# IStatus(3) : Disposable
class iStatus(iDisposable):
"""Class that wraps IStatus interface for use from Python
IStatus replaces ISC_STATUS_ARRAY. Functionality is extended - Status has separate
access to errors and warnings vectors, can hold vectors of unlimited length, itself
stores strings used in vectors avoiding need in circular strings buffer. Interface is
on purpose minimized (methods like convert it to text are moved to Util interface) in
order to simplify it's implementation by users when needed.
"""
VERSION = 3
def init(self) -> None:
"Cleanup interface, set it to initial state"
self.vtable.init(self)
def get_state(self) -> StateFlag:
"Returns state flags, may be OR-ed."
return StateFlag(self.vtable.getState(self))
def set_errors2(self, length: int, value: ByteString) -> None:
"Set contents of errors vector with length explicitly specified in a call"
self.vtable.setErrors2(self, length, value)
def set_warning2(self, length: int, value: ByteString) -> None:
"Set contents of warnings vector with length explicitly specified in a call"
self.vtable.setWarnings2(self, length, value)
def set_errors(self, value: ByteString) -> None:
"Set contents of errors vector, length is defined by value context"
self.vtable.setErrors(self, value)
def set_warnings(self, value: ByteString) -> None:
"Set contents of warnings vector, length is defined by value context"
self.vtable.setWarnings(self, value)
def get_errors(self) -> a.ISC_STATUS_ARRAY_PTR:
"Returns errors vector"
return self.vtable.getErrors(self)
def get_warning(self) -> a.ISC_STATUS_ARRAY_PTR:
"Returns warnings vector"
return self.vtable.getWarnings(self)
def clone(self) -> iStatus:
"Create clone of current interface"
return iStatus(self.vtable.clone(self))
# IPluginBase(3) : ReferenceCounted
class iPluginBase(iReferenceCounted):
"IPluginBase interface wrapper"
VERSION = 3
def set_owner(self, r: iReferenceCounted) -> None:
"Set the owner"
self.vtable.setOwner(self, r)
def get_owner(self) -> iReferenceCounted:
"Returns owner"
return iReferenceCounted(self.vtable.getOwner(self))
# IConfigEntry(3) : ReferenceCounted
class iConfigEntry(iReferenceCounted):
"Class that wraps IConfigEntry interface for use from Python"
VERSION = 3
def get_name(self) -> str:
"Returns key name"
return self.vtable.getName(self).decode()
def get_value(self) -> str:
"Returnd value string value"
return self.vtable.getValue(self).decode()
def get_int_value(self) -> int:
"Returns value as integer"
return self.vtable.getIntValue(self).value
def get_bool_value(self) -> bool:
"Returns value as boolean"
return self.vtable.getBoolValue(self).value
def get_sub_config(self, status: iStatus) -> iConfig:
"Treats sub-entries as separate configuration file and returns IConfig interface for it"
result = iConfig(self.vtable.getSubConfig(self, status))
return result
# IConfig(3) : ReferenceCounted
class iConfig(iReferenceCounted):
"Class that wraps IConfig interface for use from Python"
VERSION = 3
def find(self, name: str) -> iConfigEntry:
"Find entry by name"
result = self.vtable.find(self, self.status, name.encode())
self._check()
return iConfigEntry(result)
def find_value(self, name: str, value: str) -> iConfigEntry:
"Find entry by name and value"
result = self.vtable.findValue(self, self.status, name.encode(), value.encode())
self._check()
return iConfigEntry(result)
def find_pos(self, name: str, pos: int) -> iConfigEntry:
"""Find entry by name and position.
If configuration file contains lines::
Db=DBA
Db=DBB
Db=DBC
call to `find_pos(status, “Db”, 2)` will return entry with value DBB.
"""
result = self.vtable.findPos(self, self.status, name, pos)
self._check()
return iConfigEntry(result)
# IFirebirdConf(3) : ReferenceCounted
class iFirebirdConf_v3(iReferenceCounted):
"Class that wraps IFirebirdConf v3 interface for use from Python"
VERSION = 3
def get_key(self, name: str) -> int:
"""Returns key for configuration parameter.
Note:
If parameter with given name does not exists, returns 0xffffffff.
"""
return self.vtable.getKey(self, name.encode())
def as_integer(self, key: int) -> int:
"Returns integer value of conf. parameter"
return self.vtable.asInteger(self, key)
def as_string(self, key: int) -> str:
"Returns string value of conf. parameter"
value = self.vtable.asString(self, key)
if value is not None:
value = value.decode()
return value
def as_boolean(self, key: str) -> bool:
"Returns boolean value of conf. parameter"
return self.vtable.asBoolean(self, key)
# IFirebirdConf(4) : IFirebirdConf(3)
class iFirebirdConf(iFirebirdConf_v3):
"Class that wraps IFirebirdConf v4 interface for use from Python"
VERSION = 4
def get_version(self) -> int:
"Returns configuration version"
result = self.vtable.asBoolean(self, self.status)
self._check()
return result
# >>> Firebird 4
# IPluginManager(2) : Versioned
class iPluginManager(iVersioned):
"IPluginManager interface wrapper. This is only STUB."
VERSION = 2
# IConfigManager(2) : Versioned
class iConfigManager_v2(iVersioned):
"Class that wraps IConfigManager v2 interface for use from Python"
VERSION = 2
def get_directory(self, dirspec: DirectoryCode) -> str:
"Returns location of appropriate directory in current firebird instance"
return self.vtable.getDirectory(self, a.Cardinal(dirspec)).decode()
def get_firebird_conf(self) -> iFirebirdConf:
"Returns interface to access default configuration values (from firebird.conf)"
return iFirebirdConf(self.vtable.getFirebirdConf(self))
def get_database_conf(self, database: str) -> iFirebirdConf:
"""Returns interface to access db-specific configuration.
Takes into an account firebird.conf and appropriate part of databases.conf."""
return iFirebirdConf(self.vtable.getDatabaseConf(self, database.encode()))
def get_plugin_config(self, plugin: str) -> iConfig:
"Returns interface to access named plugin configuration"
return iConfig(self.vtable.getPluginConfig(self, plugin.encode()))
def get_install_directory(self) -> str:
"Returns directory where firebird is installed"
return self.vtable.getInstallDirectory(self).decode()
def get_root_directory(self) -> str:
"Returns root directory of current instance, in single-instance case usually matches install directory"
return self.vtable.getRootDirectory(self).decode()
# >>> Firebird 4
# IConfigManager(3) : IConfigManager(2)
class iConfigManager(iConfigManager_v2):
"Class that wraps IConfigManager v3 interface for use from Python"
VERSION = 3
def get_default_security_db(self) -> str:
"Returns default security database."
return self.vtable.getDefaultSecurityDb(self).decode()
# IBlob(3) : ReferenceCounted
class iBlob_v3(iReferenceCounted):
"Class that wraps IBlob interface for use from Python"
VERSION = 3
def get_info(self, items: bytes, buffer: bytes) -> None:
"Replaces `isc_blob_info()`"
self.vtable.getInfo(self, self.status, len(items), items, len(buffer), buffer)
self._check()
def get_segment(self, size: int, buffer: a.c_void_p, bytes_read: a.Cardinal) -> StateResult:
"""Replaces `isc_get_segment()`. Unlike it never returns `isc_segstr_eof`
and `isc_segment` errors (that are actually not errors), instead returns completion
codes `.StateResult.NO_DATA` and `.StateResult.SEGMENT`, normal return is `.StateResult.OK`.
"""
result = self.vtable.getSegment(self, self.status, size, buffer, bytes_read)
self._check()
return StateResult(result)
def put_segment(self, length: int, buffer: Any) -> None:
"Replaces `isc_put_segment()`"
self.vtable.putSegment(self, self.status, length, buffer)
self._check()
def cancel(self) -> None:
"Replaces `isc_cancel_blob()`. On success releases interface."
self.vtable.deprecatedCancel(self, self.status)
self._check()
self._refcnt -= 1
def close(self) -> None:
"Replaces `isc_close_blob()`. On success releases interface."
self.vtable.deprecatedClose(self, self.status)
self._check()
self._refcnt -= 1
def seek(self, mode: int, offset: int) -> int:
"Replaces isc_seek_blob()"
result = self.vtable.seek(self, self.status, mode, offset)
self._check()
return result
def get_info2(self, code: BlobInfoCode) -> Any:
"Returns information about BLOB"
blob_info = (0).to_bytes(20, 'little')
self.get_info(bytes([code]), blob_info)
i = 0
while blob_info[i] != isc_info_end:
_code = blob_info[i]
i += 1
if _code == code:
size = (0).from_bytes(blob_info[i: i + 2], 'little')
result = (0).from_bytes(blob_info[i + 2: i + 2 + size], 'little')
i += size + 2
return result
# IBlob(4) : IBlob(3)
class iBlob(iBlob_v3):
"Class that wraps IBlob interface for use from Python"
VERSION = 4
def cancel(self) -> None:
"Replaces `isc_cancel_blob()`. On success releases interface."
self.vtable.cancel(self, self.status)
self._check()
self._refcnt -= 1
def close(self) -> None:
"Replaces `isc_close_blob()`. On success releases interface."
self.vtable.close(self, self.status)
self._check()
self._refcnt -= 1
# ITransaction(3) : ReferenceCounted
class iTransaction_v3(iReferenceCounted):
"Class that wraps ITransaction interface for use from Python"
VERSION = 3
def get_info(self, items: bytes, buffer: bytes) -> None:
"Replaces `isc_transaction_info()`"
self.vtable.getInfo(self, self.status, len(items), items, len(buffer), buffer)
self._check()
def prepare(self, message: bytes | None=None) -> None:
"Replaces `isc_prepare_transaction2()`"
self.vtable.prepare(self, self.status, 0 if message is None else len(message), message)
self._check()
def commit(self) -> None:
"Replaces `isc_commit_transaction()`"
self.vtable.deprecatedCommit(self, self.status)
self._check()
self._refcnt -= 1
def commit_retaining(self) -> None:
"Replaces `isc_commit_retaining()`"
self.vtable.commitRetaining(self, self.status)
self._check()
def rollback(self) -> None:
"Replaces `isc_rollback_transaction()`"
self.vtable.deprecatedRollback(self, self.status)
self._check()
self._refcnt -= 1
def rollback_retaining(self) -> None:
"Replaces `isc_rollback_retaining()`"
self.vtable.rollbackRetaining(self, self.status)
self._check()
def disconnect(self) -> None:
"Replaces `fb_disconnect_transaction()`"
self.vtable.deprecatedDisconnect(self, self.status)
self._check()
def join(self, transaction: iTransaction) -> iTransaction:
"""Joins current transaction and passed as parameter transaction into
single distributed transaction (using Dtc). On success both current transaction
and passed as parameter transaction are released and should not be used any more."""
result = self.vtable.join(self, self.status, transaction)
self._check()
self._refcnt -= 1
transaction._refcnt -= 1
return iTransaction(result)
def validate(self, attachment: iAttachment) -> iTransaction:
"This method is used to support distributed transactions coordinator"
result = self.vtable.validate(self, self.status, attachment)
self._check()
return self if result is not None else None
def enter_dtc(self) -> iTransaction: # pragma: no cover
"This method is used to support distributed transactions coordinator"
raise InterfaceError("Method not supported")
# ITransaction(4) : ITransaction(3)
class iTransaction(iTransaction_v3):
"Class that wraps ITransaction interface for use from Python"
VERSION = 4
def commit(self) -> None:
"Replaces `isc_commit_transaction()`"
self.vtable.commit(self, self.status)
self._check()
self._refcnt -= 1
def rollback(self) -> None:
"Replaces `isc_rollback_transaction()`"
self.vtable.rollback(self, self.status)
self._check()
self._refcnt -= 1
def disconnect(self) -> None:
"Replaces `fb_disconnect_transaction()`"
self.vtable.disconnect(self, self.status)
self._check()
# IMessageMetadata(3) : ReferenceCounted
class iMessageMetadata_v3(iReferenceCounted):
"Class that wraps IMessageMetadata v3 interface for use from Python"
VERSION = 3
def get_count(self) -> int:
"""Returns number of fields/parameters in a message. In all calls,
containing index parameter, it's value should be: 0 <= index < getCount()."""
result = self.vtable.getCount(self, self.status)
self._check()
return result
def get_field(self, index: int) -> str:
"Returns field name"
result = self.vtable.getField(self, self.status, index).decode()
self._check()
return result
def get_relation(self, index: int) -> str:
"Returns relation name (from which given field is selected)"
result = self.vtable.getRelation(self, self.status, index).decode()
self._check()
return result
def get_owner(self, index: int) -> str:
"Returns relation's owner name"
result = self.vtable.getOwner(self, self.status, index).decode()
self._check()
return result
def get_alias(self, index: int) -> str:
"Returns field alias"
result = self.vtable.getAlias(self, self.status, index).decode()
self._check()
return result
def get_type(self, index: int) -> SQLDataType:
"Returns field SQL type"
result = self.vtable.getType(self, self.status, index)
self._check()
return SQLDataType(result)
def is_nullable(self, index: int) -> bool:
"Returns True if field is nullable"
result = self.vtable.isNullable(self, self.status, index)
self._check()
return result
def get_subtype(self, index: int) -> int:
"Returns blob field subtype (0 - binary, 1 - text, etc.)"
result = self.vtable.getSubType(self, self.status, index)
self._check()
return result
def get_length(self, index: int) -> int:
"Returns maximum field length"
result = self.vtable.getLength(self, self.status, index)
self._check()
return result
def get_scale(self, index: int) -> int:
"Returns scale factor for numeric field"
result = self.vtable.getScale(self, self.status, index)
self._check()
return result
def get_charset(self, index: int) -> int:
"Returns character set for character field and text blob"
result = self.vtable.getCharSet(self, self.status, index)
self._check()
return result
def get_offset(self, index: int) -> int:
"Returns offset of field data in message buffer (use it to access data in message buffer)"
result = self.vtable.getOffset(self, self.status, index)
self._check()
return result
def get_null_offset(self, index: int) -> int:
"Returns offset of null indicator for a field in message buffer"
result = self.vtable.getNullOffset(self, self.status, index)
self._check()
return result
def get_builder(self) -> iMetadataBuilder:
"Returns MetadataBuilder interface initialized with this message metadata"
result = iMetadataBuilder(self.vtable.getBuilder(self, self.status))
self._check()
return result
def get_message_length(self) -> int:
"Returns length of message buffer (use it to allocate memory for the buffer)"
result = self.vtable.getMessageLength(self, self.status)
self._check()
return result
# >>> Firebird 4
# IMessageMetadata(4) : IMessageMetadata(3)
class iMessageMetadata(iMessageMetadata_v3):
"Class that wraps IMessageMetadata v4 interface for use from Python"
VERSION = 4
def get_alignment(self) -> int:
"""Returns alignment required for message buffer.
"""
result = self.vtable.getAlignment(self, self.status)
self._check()
return result
def get_aligned_length(self) -> int:
"""Returns length of message buffer taking into an account alignment requirements
(use it to allocate memory for an array of buffers and navigate through that array).
"""
result = self.vtable.getAlignedLength(self, self.status)
self._check()
return result
# IMetadataBuilder(3) : ReferenceCounted
class iMetadataBuilder_v3(iReferenceCounted):
"Class that wraps IMetadataBuilder v3 interface for use from Python"
VERSION = 3
def set_type(self, index: int, field_type: SQLDataType) -> None:
"Set SQL type of a field"
self.vtable.setType(self, self.status, index, field_type)
self._check()
def set_subtype(self, index: int, subtype: int) -> None:
"Set blob field subtype"
self.vtable.setSubType(self, self.status, index, subtype)
self._check()
def set_length(self, index: int, length: int) -> None:
"Set maximum length of character field"
self.vtable.setLength(self, self.status, index, length)
self._check()
def set_charset(self, index: int, charset: int) -> None:
"Set character set for character field and text blob"
self.vtable.setCharSet(self, self.status, index, charset)
self._check()
def set_scale(self, index: int, scale: int) -> None:
"Set scale factor for numeric field"
self.vtable.setScale(self, self.status, index, scale)
self._check()
def truncate(self, count: int) -> None:
"Truncate message to contain not more than count fields"
self.vtable.truncate(self, self.status, count)
self._check()
def move_name_to_index(self, name: str, index: int) -> None:
"Reorganize fields in a message - move field 'name' to given position"
self.vtable.moveNameToIndex(self, self.status, name.encode(), index)
self._check()
def remove(self, index: int) -> None:
"Remove field"
self.vtable.remove(self, self.status, index)
self._check()
def add_field(self) -> int:
"Add field"
result = self.vtable.addField(self, self.status)
self._check()
return result
def get_metadata(self) -> iMessageMetadata:
"Returns MessageMetadata interface built by this builder"
result = iMessageMetadata(self.vtable.getMetadata(self, self.status))
self._check()
return result
# >>> Firebird 4
# IMetadataBuilder(4) : IMetadataBuilder(3)
class iMetadataBuilder(iMetadataBuilder_v3):
"Class that wraps IMetadataBuilder v4 interface for use from Python"
VERSION = 4
def set_field(self, index: int, field: str) -> None:
"Set field name"
self.vtable.setField(self, self.status, index, field.encode())
self._check()
def set_relation(self, index: int, relation: str) -> None:
"Set relation name"
self.vtable.setRelation(self, self.status, index, relation.encode())
self._check()
def set_owner(self, index: int, owner: str) -> None:
"Set owner name"
self.vtable.setOwner(self, self.status, index, owner.encode())
self._check()
def set_alias(self, index: int, alias: str) -> None:
"Set the alias"
self.vtable.setAlias(self, self.status, index, alias.encode())
self._check()
# IResultSet(3) : ReferenceCounted
class iResultSet_v3(iReferenceCounted):
"Class that wraps IResultSet interface for use from Python"
VERSION = 3
def fetch_next(self, message: bytes) -> StateResult:
"""Fetch next record, replaces isc_dsql_fetch(). This method (and other
fetch methods) returns completion code Status::RESULT_NO_DATA when EOF is reached,
Status::RESULT_OK on success."""
result = self.vtable.fetchNext(self, self.status, message)
self._check()
return StateResult(result)
def fetch_prior(self, message: bytes) -> StateResult:
"Fetch previous record"
result = self.vtable.fetchPrior(self, self.status, message)
self._check()
return StateResult(result)
def fetch_first(self, message: bytes) -> StateResult:
"Fetch first record"
result = self.vtable.fetchFirst(self, self.status, message)
self._check()
return StateResult(result)
def fetch_last(self, message: bytes) -> StateResult:
"Fetch last record"
result = self.vtable.fetchLast(self, self.status, message)
self._check()
return StateResult(result)
def fetch_absolute(self, position: int, message: bytes) -> StateResult:
"Fetch record by it's absolute position in result set"
result = self.vtable.fetchAbsolute(self, self.status, position, message)
self._check()
return StateResult(result)
def fetch_relative(self, offset: int, message: bytes) -> StateResult:
"Fetch record by position relative to current"
result = self.vtable.fetchRelative(self, self.status, offset, message)
self._check()
return StateResult(result)
def is_eof(self) -> bool:
"Check for EOF"
result = self.vtable.isEof(self, self.status)
self._check()
return result
def is_bof(self) -> bool:
"Check for BOF"
result = self.vtable.isBof(self, self.status)
self._check()
return result
def get_metadata(self) -> iMessageMetadata:
"""Get metadata for messages in result set, specially useful when result
set is opened by IAttachment::openCursor() call with NULL output metadata format
parameter (this is the only way to obtain message format in this case)"""
result = self.vtable.getMetadata(self, self.status)
self._check()
return iMessageMetadata(result)
def close(self) -> None:
"Close result set, releases interface on success"
self.vtable.deprecatedClose(self, self.status)
self._check()
self._refcnt -= 1
def set_delayed_output_format(self, fmt: iMessageMetadata) -> None:
"""Important:
This item is for ISC API emulation only. It may be gone in future versions.
Please do not use it!
"""
self.vtable.setDelayedOutputFormat(self, self.status, fmt)
self._check()
# IResultSet(4) : ReferenceCounted
class iResultSet_v4(iResultSet_v3):
"Class that wraps IResultSet interface for use from Python"
VERSION = 4
def close(self) -> None:
"Close result set, releases interface on success"
self.vtable.close(self, self.status)
self._check()
self._refcnt -= 1
# IResultSet(5) : ReferenceCounted
class iResultSet(iResultSet_v4):
"Class that wraps IResultSet interface for use from Python"
VERSION = 5
def get_info(self, items: bytes, buffer: bytes) -> None:
"Returns information about result set."
self.vtable.getInfo(self, self.status, len(items), items, len(buffer), buffer)
self._check()
def close(self) -> None:
"Close result set, releases interface on success"
self.vtable.close(self, self.status)
self._check()
self._refcnt -= 1
# IStatement(3) : ReferenceCounted
class iStatement_v3(iReferenceCounted):
"Class that wraps IStatement v3 interface for use from Python"
VERSION = 3
def get_info(self, items: bytes, buffer: bytes) -> None:
"Replaces `isc_dsql_sql_info()`"
self.vtable.getInfo(self, self.status, len(items), items, len(buffer), buffer)
self._check()
def get_type(self) -> StatementType:
"Statement type, currently can be found only in firebird sources in `dsql/dsql.h`"
result = self.vtable.getType(self, self.status)
self._check()
return StatementType(result)
def get_plan(self, detailed: bool) -> str:
"Returns statement execution plan"
result = self.vtable.getPlan(self, self.status, detailed)
self._check()
return result.decode() if result else result
def get_affected_records(self) -> int:
"Returns number of records affected by statement"
result = self.vtable.getAffectedRecords(self, self.status)
self._check()
return result
def get_input_metadata(self) -> iMessageMetadata:
"Returns parameters metadata"
result = self.vtable.getInputMetadata(self, self.status)
self._check()
return iMessageMetadata(result)
def get_output_metadata(self) -> iMessageMetadata:
"Returns output values metadata"
result = self.vtable.getOutputMetadata(self, self.status)
self._check()
return iMessageMetadata(result)
def execute(self, transaction: iTransaction, in_meta: iMessageMetadata, in_buffer: bytes,
out_meta: iMessageMetadata, out_buffer: bytes) -> None:
"""Executes any SQL statement except returning multiple rows of data.
Partial analogue of `isc_dsql_execute2()` - in and out XSLQDAs replaced with input
and output messages with appropriate buffers."""
result = self.vtable.execute(self, self.status, transaction, in_meta, in_buffer, out_meta, out_buffer)
self._check()
transaction._as_parameter_ = result
def open_cursor(self, transaction: iTransaction, in_meta: iMessageMetadata, in_buffer: bytes,
out_meta: iMessageMetadata, flags: CursorFlag) -> iResultSet:
"""Executes SQL statement potentially returning multiple rows of data.
Returns ResultSet interface which should be used to fetch that data. Format of
output data is defined by outMetadata parameter, leaving it NULL default format
may be used. Parameter flags is needed to open bidirectional cursor setting it's
value to IStatement::CURSOR_TYPE_SCROLLABLE."""
result = self.vtable.openCursor(self, self.status, transaction, in_meta, in_buffer, out_meta, flags)
self._check()
return iResultSet(result)
def set_cursor_name(self, name: str) -> None:
"Replaces `isc_dsql_set_cursor_name()`"
self.vtable.setCursorName(self, self.status, name.encode())
self._check()
def free(self) -> None:
"Free statement, releases interface on success"
self.vtable.deprecatedFree(self, self.status)
self._check()
self._refcnt -= 1
def get_flags(self) -> StatementFlag:
"Returns flags describing how this statement should be executed, simplified replacement of getType() method"
result = self.vtable.getFlags(self, self.status)
self._check()
return StatementFlag(result)
# >>> Firebird 4
# IStatement(4) : IStatement(3)
class iStatement_v4(iStatement_v3):
"Class that wraps IStatement v4 interface for use from Python"
VERSION = 4
def get_timeout(self) -> int:
"Return statement timeout"
result = self.vtable.getTimeout(self, self.status)
self._check()
return result
def set_timeout(self, timeout: int) -> None:
"Set the statement timeout"
self.vtable.setTimeout(self, self.status, timeout)
self._check()
def create_batch(self, in_meta: iMessageMetadata, params: bytes) -> iBatch:
"Create new batch"
result = self.vtable.createBatch(self, self.status, in_meta, len(params), params)
self._check()
return iBatch(result)
# IStatement(5) : IStatement(4)
class iStatement(iStatement_v4):
"Class that wraps IStatement v4 interface for use from Python"
VERSION = 5
def free(self) -> None:
"Free statement, releases interface on success"
self.vtable.free(self, self.status)
self._check()
self._refcnt -= 1
# IBatch(3) : ReferenceCounted
class iBatch_v3(iReferenceCounted):
"Class that wraps IBatch interface for use from Python"
VERSION = 3
TAG_MULTIERROR = 1
TAG_RECORD_COUNTS = 2
TAG_BUFFER_BYTES_SIZE = 3
TAG_BLOB_POLICY = 4
TAG_DETAILED_ERRORS = 5
INF_BUFFER_BYTES_SIZE = 10
INF_DATA_BYTES_SIZE = 11
INF_BLOBS_BYTES_SIZE = 12
INF_BLOB_ALIGNMENT = 13
INF_BLOB_HEADER = 14
BLOB_NONE = 0
BLOB_ID_ENGINE = 1
BLOB_ID_USER = 2
BLOB_STREAM = 3
BLOB_SEGHDR_ALIGN = 2
def add(self, count: int, in_buffer: bytes) -> None:
"""Adds count messages from inBuffer to the batch. Total size of messages that can
be added to the batch is limited by TAG_BUFFER_BYTES_SIZE parameter of batch creation.
"""
self.vtable.add(self, self.status, count, in_buffer)
self._check()
def add_blob(self, length: int, in_buffer: bytes, id_: a.ISC_QUAD, params: bytes) -> None:
"""Adds single blob having length bytes from `in_buffer` to the batch,
blob identifier is located at `id_` address. If blob should be created with
non-default parameters BPB may be passed (format matches one used in
`~.iAttachment_v3.create_blob`). Total size of inline blobs that can be added to the
batch (including optional BPBs, blob headers, segment sizes and taking into an
accoount alignment) is limited by TAG_BUFFER_BYTES_SIZE parameter of batch creation
(affects all blob-oriented methods except `register_blob()`).
"""
self.vtable.addBlob(self, self.status, length, in_buffer, byref(id_), len(params), params)
self._check()
def append_blob_data(self, length: int, in_buffer: bytes) -> None:
"""Extend last added blob: append length bytes taken from `in_buffer` to it.
"""
self.vtable.appendBlobData(self, self.status, length, in_buffer)
self._check()
def add_blob_stream(self, length: int, in_buffer: bytes) -> None:
"""Adds blob data (this can be multiple objects or part of single blob) to the batch.
Header of each blob in the stream is aligned at `get_blob_alignment()` boundary
and contains 3 fields: first - 8-bytes blob identifier (in ISC_QUAD format),
second - 4-bytes length of blob, third - 4-bytes length of BPB. Blob header should
not cross boundaries of buffer in this function call. BPB data is placed right after
header, blob data goes next. Length of blob includes BPB (if it present). All data
may be distributed between multiple `add_blob_stream()` calls. Blob data in turn
may be structured in case of segmented blob, see chapter “Modifying data in a batch”
in `Using_OO_API` guide.
"""
self.vtable.addBlobStream(self, self.status, length, in_buffer)
self._check()
def register_blob(self, existing: a.ISC_QUAD, id_: a.ISC_QUAD):
"""Makes it possible to use in batch blobs added using standard Blob interface.
This function contains 2 ISC_QUAD* parameters, it's important not to mix them -
first parameter (`existing`) is a blob identifier, already added out of batch scope,
second (`id_`) is blob identifier that will be placed in a message in this batch.
"""
self.vtable.registerBlob(self, self.status, byref(existing), byref(id_))
self._check()
def execute(self, transaction: iTransaction) -> iBatchCompletionState:
"""Execute batch with parameters passed to it in the messages. If parameter
MULTIERROR is not set in parameters block when creating the batch execution will be
stopped after first error, in MULTIERROR mode an unlimited number of errors can
happen, after an error execution is continued from the next message. This function
returns `.iBatchCompletionState` interface that contains all requested information
about the results of batch execution.
"""
result = self.vtable.execute(self, self.status, transaction)
self._check()
return iBatchCompletionState(result)
def cancel(self) -> None:
"""Clear messages and blobs buffers, return batch to a state it had right after
creation.
Note:
Being reference counted interface batch does not contain any special function to
close it, please use release() for this purposes.
"""
self.vtable.cancel(self, self.status)
self._check()
def get_blob_alignment(self) -> int:
"""Returns required alignment for the data placed into the buffer of `.add_blob_stream()`.
"""
result = self.vtable.getBlobAlignment(self, self.status)
self._check()
return result
def get_metadata(self) -> iMessageMetadata:
"""Returns format of metadata used in batch's messages.
"""
result = self.vtable.getMetadata(self, self.status)
self._check()
return iMessageMetadata(result)
def set_default_bpb(self, bpb: bytes) -> None:
"""Sets BPB which will be used for all blobs missing non-default BPB. Must be called
before adding any message or blob to batch.
"""
self.vtable.setDefaultBpb(self, self.status, len(bpb), bpb)
self._check()
def close(self) -> None:
"""Sets BPB which will be used for all blobs missing non-default BPB. Must be called
before adding any message or blob to batch.
"""
self.vtable.deprecatedClose(self, self.status)
self._check()
# IBatch(4) : IBatch(3)
class iBatch(iBatch_v3):
"Class that wraps IBatch interface for use from Python"
VERSION = 4
def close(self) -> None:
"""Sets BPB which will be used for all blobs missing non-default BPB. Must be called
before adding any message or blob to batch.
"""
self.vtable.close(self, self.status)
self._check()
def get_info(self, items: bytes, buffer: bytes) -> None:
"""Requests information about batch.
"""
self.vtable.getInfo(self, self.status, len(items), items, len(buffer), buffer)
self._check()
# IBatchCompletionState(3) : Disposable
class iBatchCompletionState(iDisposable):
"Class that wraps IBatchCompletionState interface for use from Python"
VERSION = 3
EXECUTE_FAILED = -1
SUCCESS_NO_INFO = -2
NO_MORE_ERRORS = 0xffffffff
def get_size(self) -> int:
"""Returns the total number of processed messages.