10000 Optimizations; Fixed test for v4.0; Fixed problems with system PSQL f… · FirebirdSQL/python3-lib@6feab7b · GitHub
[go: up one dir, main page]

Skip to content

Commit 6feab7b

Browse files
committed
Optimizations; Fixed test for v4.0; Fixed problems with system PSQL functions and packages; Fixed bug in PSQL function parameters
1 parent c1aee17 commit 6feab7b

File tree

12 files changed

+448
-166
lines changed

12 files changed

+448
-166
lines changed

firebird/lib/log.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
from typing import List, Dict, Any, Iterable, Optional, Union
4141
from datetime import datetime
4242
from dataclasses import dataclass
43+
from contextlib import suppress
4344
from firebird.base.types import Error, STOP, Sentinel
4445
from .logmsgs import identify_msg, Severity, Facility
4546

@@ -87,11 +88,9 @@ def push(self, line: Union[str, Sentinel]) -> Optional[LogMessage]:
8788
if len(items) >= 6:
8889
# potential new entry
8990
new_entry = False
90-
try:
91+
with suppress(ValueError):
9192
datetime.strptime(' '.join(items[len(items)-5:]), '%a %b %d %H:%M:%S %Y')
9293
new_entry = True
93-
except ValueError:
94-
pass
9594
if new_entry:
9695
if self.__buffer:
9796
result = self.parse_entry(self.__buffer)
@@ -124,9 +123,7 @@ def parse_entry(self, log_entry: List[str]) -> LogMessage:
124123
log_msg = found[0]
125124
return LogMessage(origin, timestamp, log_msg.severity, log_msg.msg_id,
126125
log_msg.facility, log_msg.get_pattern(found[2]), found[1])
127-
else:
128-
return LogMessage(origin, timestamp, Severity.UNKNOWN, 0, Facility.UNKNOWN,
129-
msg, {})
126+
return LogMessage(origin, timestamp, Severity.UNKNOWN, 0, Facility.UNKNOWN, msg, {})
130127
def parse(self, lines: Iterable):
131128
"""Parse output from Firebird log.
132129

firebird/lib/logmsgs.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -966,7 +966,7 @@ def get_pattern(self, without_optional: bool) -> str:
966966
_r_msgs.append(msg)
967967
else:
968968
parts = msg.msg_format[0].split()
969-
_h_msgs.setdefault(parts[0], list()).append(msg)
969+
_h_msgs.setdefault(parts[0], []).append(msg)
970970

971971
def identify_msg(msg: str) -> Optional[Tuple[MsgDesc, Dict[str, Any], bool]]:
972972
"""Identify Firebird log message.

firebird/lib/monitor.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ def __init__(self, connection: Connection):
108108
"""
109109
self._con: Connection = connection
110110
self._ic: Cursor = self._con.transaction_manager(tpb(Isolation.READ_COMMITTED_RECORD_VERSION,
111-
access=TraAccessMode.READ)).cursor()
111+
access_mode=TraAccessMode.READ)).cursor()
112112
self._ic._logging_id_ = 'monitor.internal_cursor'
113113
self.__internal: bool = False
114114
self._con_id: int = connection.info.id
@@ -265,7 +265,7 @@ class InfoItem:
265265
def __init__(self, monitor: Monitor, attributes: Dict[str, Any]):
266266
#: Weak reference to parent `.Monitor` instance.
267267
self.monitor: Monitor = monitor if isinstance(monitor, weakref.ProxyType) else weakref.proxy(monitor)
268-
self._attributes: Dict[str, Any] = dict(attributes)
268+
self._attributes: Dict[str, Any] = attributes
269269
def _strip_attribute(self, attr: str) -> None:
270270
if self._attributes.get(attr):
271271
self._attributes[attr] = self._attributes[attr].strip()

firebird/lib/schema.py

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -885,7 +885,7 @@ def bind(self, connection: Connection) -> Schema:
885885
raise Error("Call to 'bind' not allowed for embedded Schema.")
886886
self._con = connection
887887
self._ic = self._con.transaction_manager(tpb(Isolation.READ_COMMITTED_RECORD_VERSION,
888-
access=TraAccessMode.READ)).cursor()
888+
access_mode=TraAccessMode.READ)).cursor()
889889
self._ic._logging_id_ = 'schema.internal_cursor'
890890
self.__clear()
891891
self.ods = self._con.info.ods
@@ -1116,7 +1116,7 @@ def get_item(self, name: str, itype: ObjectType, subname: str=None) -> SchemaIte
11161116
return self.all_functions.get(name)
11171117
elif itype is ObjectType.COLLATION:
11181118
return self.collations.get(name)
1119-
elif itype in [ObjectType.PACKAGE, ObjectType.PACKAGE_BODY]: # Package
1119+
elif itype in (ObjectType.PACKAGE, ObjectType.PACKAGE_BODY): # Package
11201120
return self.packages.get(name)
11211121
def get_metadata_ddl(self, *, sections=SCRIPT_DEFAULT_ORDER) -> List[str]:
11221122
"""Return list of DDL SQL commands for creation of specified categories of database objects.
@@ -1174,7 +1174,8 @@ def view_dependencies(item):
11741174
script.append(domain.get_sql_for('create'))
11751175
elif section == Section.PACKAGE_DEFS:
11761176
for package in self.packages:
1177-
script.append(package.get_sql_for('create'))
1177+
if not package.is_sys_object():
1178+
script.append(package.get_sql_for('create'))
11781179
elif section == Section.FUNCTION_DEFS:
11791180
for func in (x for x in self.functions if
11801181
not x.is_external() and
@@ -1211,7 +1212,8 @@ def view_dependencies(item):
12111212
script.append(view.get_sql_for('create'))
12121213
elif section == Section.PACKAGE_BODIES:
12131214
for package in self.packages:
1214-
script.append(package.get_sql_for('create', body=True))
1215+
if not package.is_sys_object():
1216+
script.append(package.get_sql_for('create', body=True))
12151217
elif section == Section.PROCEDURE_BODIES:
12161218
for proc in (x for x in self.procedures if not x.is_packaged()):
12171219
script.append('ALTER' + proc.get_sql_for('create')[6:])
@@ -1232,12 +1234,12 @@ def view_dependencies(item):
12321234
and not x.subject.is_sys_object()):
12331235
script.append(priv.get_sql_for('grant'))
12341236
elif section == Section.COMMENTS:
1235-
for objects in [self.character_sets, self.collations,
1237+
for objects in (self.character_sets, self.collations,
12361238
self.exceptions, self.domains,
12371239
self.generators, self.tables,
12381240
self.indices, self.views,
12391241
self.triggers, self.procedures,
1240-
self.functions, self.roles]:
1242+
self.functions, self.roles):
12411243
for obj in objects:
12421244
if obj.description is not None:
12431245
script.append(obj.get_sql_for('comment'))
@@ -1653,7 +1655,7 @@ def __init__(self, schema: Schema, attributes: Dict[str, Any]):
16531655
#: Weak reference to parent `.Schema` instance.
16541656
self.schema: Schema = schema if isinstance(schema, weakref.ProxyType) else weakref.proxy(schema)
16551657
self._type_code: List[ObjectType] = []
1656-
self._attributes: Dict[str, Any] = dict(attributes)
1658+
self._attributes: Dict[str, Any] = attributes
16571659
self._actions: List[str] = []
16581660
def _strip_attribute(self, attr: str) -> None:
16591661
if self._attributes.get(attr):
@@ -1668,7 +1670,7 @@ def _needs_quoting(self, ident: str) -> bool:
16681670
return False
16691671
if self.schema.opt_always_quote:
16701672
return True
1671-
if len(ident) >= 1 and ident[0] not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
1673+
if ident and ident[0] not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
16721674
return True
16731675
for char in ident:
16741676
if char not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$_':
@@ -2596,7 +2598,7 @@ def datatype(self) -> str:
25962598
precision_known = False
25972599
if self.field_type in (FieldType.SHORT, FieldType.LONG, FieldType.INT64):
25982600
if self.precision is not None:
2599-
if self.sub_type in [FieldSubType.NUMERIC, FieldSubType.DECIMAL]:
2601+
if self.sub_type in (FieldSubType.NUMERIC, FieldSubType.DECIMAL):
26002602
l.append(f'{INTEGRAL_SUBTYPES[self.sub_type]}({self.precision}, {-self.scale})')
26012603
precision_known = True
26022604
if not precision_known:
@@ -2710,7 +2712,7 @@ def dependent(self) -> SchemaItem:
27102712
return None
27112713
elif self.dependent_type == 17: # Collation
27122714
return self.schema.collations.get(self.dependent_name)
2713-
elif self.dependent_type in [18, 19]: # Package + package body
2715+
elif self.dependent_type in (18, 19): # Package + package body
27142716
return self.schema.packages.get(self.dependent_name)
27152717
return None
27162718
@property
@@ -2904,8 +2906,7 @@ def trigger_names(self) -> List[str]:
29042906
"""
29052907
if self.is_check():
29062908
return self._attributes['RDB$TRIGGER_NAME']
2907-
else:
2908-
return []
2909+
return []
29092910
@property
29102911
def triggers(self) -> DataList[Trigger]:
29112912
"""List of triggers that enforce the CHECK constraint.
@@ -3056,12 +3057,12 @@ def _get_name(self) -> str:
30563057
def is_gtt(self) -> bool:
30573058
"""Returns True if table is GLOBAL TEMPORARY table.
30583059
"""
3059-
return self.table_type in [RelationType.GLOBAL_TEMPORARY_DELETE,
3060-
RelationType.GLOBAL_TEMPORARY_PRESERVE]
3060+
return self.table_type in (RelationType.GLOBAL_TEMPORARY_DELETE,
3061+
RelationType.GLOBAL_TEMPORARY_PRESERVE)
30613062
def is_persistent(self) -> bool:
30623063
"""Returns True if table is persistent one.
30633064
"""
3064-
return self.table_type in [RelationType.PERSISTENT, RelationType.EXTERNAL]
3065+
return self.table_type in (RelationType.PERSISTENT, RelationType.EXTERNAL)
30653066
def is_external(self) -> bool:
30663067
"""Returns True if table is external table.
30673068
"""
@@ -3938,8 +3939,7 @@ def __init__(self, schema: Schema, function: Function, attributes: Dict[str, Any
39383939
self._strip_attribute('RDB$RELATION_NAME')
39393940
self._strip_attribute('RDB$DESCRIPTION')
39403941
def _get_name(self) -> str:
3941-
return self.argument_name if self.argument_name \
3942-
else f'{self.function.name}_{self.position}'
3942+
return self.argument_name or f'{self.function.name}_{self.position}'
39433943
def get_sql_definition(self) -> str:
39443944
"""Returns SQL definition for parameter.
39453945
"""
@@ -3962,16 +3962,16 @@ def is_by_value(self) -> bool:
39623962
def is_by_reference(self) -> bool:
39633963
"""Returns True if argument is passed by reference.
39643964
"""
3965-
return self.mechanism in [Mechanism.BY_REFERENCE, Mechanism.BY_REFERENCE_WITH_NULL]
3965+
return self.mechanism in (Mechanism.BY_REFERENCE, Mechanism.BY_REFERENCE_WITH_NULL)
39663966
def is_by_descriptor(self, any=False) -> bool:
39673967
"""Returns True if argument is passed by descriptor.
39683968
39693969
Arguments:
39703970
any: If True, method returns True if any kind of descriptor is used (including
39713971
BLOB and ARRAY descriptors).
39723972
"""
3973-
return self.mechanism in [Mechanism.BY_VMS_DESCRIPTOR, Mechanism.BY_ISC_DESCRIPTOR,
3974-
Mechanism.BY_SCALAR_ARRAY_DESCRIPTOR] if any \
3973+
return self.mechanism in (Mechanism.BY_VMS_DESCRIPTOR, Mechanism.BY_ISC_DESCRIPTOR,
3974+
Mechanism.BY_SCALAR_ARRAY_DESCRIPTOR) if any \
39753975
else self.mechanism == Mechanism.BY_VMS_DESCRIPTOR
39763976
def is_with_null(self) -> bool:
39773977
"""Returns True if argument is passed by reference with NULL support.
@@ -4016,7 +4016,7 @@ def mechanism(self) -> Mechanism:
40164016
def field_type(self) -> FieldType:
40174017
"""Number code of the data type defined for the argument.
40184018
"""
4019-
return None if (code := self._attributes['RDB$FIELD_TYPE']) is None else FieldType(code)
4019+
return None if (code := self._attributes['RDB$FIELD_TYPE']) in (None, 0) else FieldType(code)
40204020
@property
40214021
def length(self) -> int:
40224022
"""Length of the argument in bytes.
@@ -4070,7 +4070,7 @@ def datatype(self) -> str:
40704070
precision_known = False
40714071
if self.field_type in (FieldType.SHORT, FieldType.LONG, FieldType.INT64):
40724072
if self.precision != None:
4073-
if self.sub_type in [FieldSubType.NUMERIC, FieldSubType.DECIMAL]:
4073+
if self.sub_type in (FieldSubType.NUMERIC, FieldSubType.DECIMAL):
40744074
l.append(f'{INTEGRAL_SUBTYPES[self.sub_type]}({self.precision}, {-self.scale})')
40754075
precision_known = True
40764076
if not precision_known:
@@ -4224,7 +4224,7 @@ def _get_create_sql(self, **params) -> str:
42244224
def _get_alter_sql(self, **params) -> str:
42254225
self._check_params(params, ['arguments', 'returns', 'declare', 'code'])
42264226
arguments = params.get('arguments')
4227-
for par in ['returns', 'code']:
4227+
for par in ('returns', 'code'):
42284228
if par not in params:
42294229
raise ValueError(f"Missing required parameter: '{par}'")
42304230
returns = params.get('returns')
@@ -4280,7 +4280,7 @@ def _load_arguments(self, mock: Dict[str, Any]=None) -> None:
42804280
'RDB$ARGUMENT_MECHANISM', 'RDB$FIELD_NAME', 'RDB$RELATION_NAME',
42814281
'RDB$SYSTEM_FLAG', 'RDB$DESCRIPTION']
42824282
self.__arguments = DataList((FunctionArgument(self.schema, self, row) for row in
4283-
(mock if mock else
4283+
(mock or
42844284
self.schema._select("""select %s from rdb$function_arguments
42854285
where rdb$function_name = ? order by rdb$argument_position""" % ','.join(cols), (self.name,)))),
42864286
FunctionArgument, frozen=True)

0 commit comments

Comments
 (0)
0