22
33from collections import namedtuple
44from enum import IntEnum
5+ from functools import wraps
56from itertools import groupby
67from itertools import starmap
78from operator import attrgetter
1011from typing import Iterator
1112from typing import List
1213from typing import Optional
13- from typing import Union
1414from typing import Tuple
15- from typing import NamedTuple
15+ from typing import Union
1616
1717import cx_Oracle as oracle
1818
@@ -36,7 +36,7 @@ class ObjectTypes(IntEnum):
3636 type = 13
3737
3838
39- class NotFound (Exception ):
39+ class NotFound (AttributeError ):
4040 pass
4141
4242
@@ -260,15 +260,6 @@ def group_by_overload(arguments: Iterator[Argument]) -> List[Overload]:
260260 ] or [Overload (arguments = [])]
261261
262262
263- def filter_match (matches : Iterator [Overload ]) -> Overload :
264- matches = list (matches )
265- if len (matches ) > 1 :
266- raise ValueError ("Arguments matched with too many subprograms" )
267- elif len (matches ) == 0 :
268- raise ValueError ("Arguments do not match subprogram" )
269- return matches [0 ]
270-
271-
272263def plsql_record (attributes ) -> Any :
273264 return namedtuple ("Record" , (attribute .name .lower () for attribute in attributes ))
274265
@@ -277,8 +268,8 @@ def plsql_record(attributes) -> Any:
277268def to_python (value ):
278269 if isinstance (value , oracle .Object ):
279270 if value .type .attributes :
280- return record_converter (value )
281- return list_converter (value ) # todo: list/dict
271+ return record_out_converter (value )
272+ return list_out_converter (value ) # todo: list/dict
282273 return value
283274
284275
@@ -288,29 +279,29 @@ def to_record(value, record):
288279 )
289280
290281
291- def list_converter (value ):
282+ def list_out_converter (value ):
292283 if value .type .elementType :
293284 attributes = value .type .elementType .attributes
294285 if attributes :
295286 record = plsql_record (attributes )
296287 return [to_record (val , record ) for val in value .aslist ()]
297288 # todo: list/dict
298- return [list_converter (val ) for val in value .aslist ()]
289+ return [list_out_converter (val ) for val in value .aslist ()]
299290 return value .aslist ()
300291
301292
302- def dict_converter (value ):
293+ def dict_out_coverter (value ):
303294 if value .type .elementType :
304295 attributes = value .type .elementType .attributes
305296 if attributes :
306297 record = plsql_record (attributes )
307298 return {key : to_record (val , record ) for key , val in value .asdict ().items ()}
308299 # todo: list/dict
309- return {key : dict_converter (val ) for key , val in value .asdict ().items ()}
300+ return {key : dict_out_coverter (val ) for key , val in value .asdict ().items ()}
310301 return value .asdict ()
311302
312303
313- def record_converter (value , record = None ):
304+ def record_out_converter (value , record = None ):
314305 attributes = value .type .attributes
315306 record = record or plsql_record (attributes )
316307 return to_record (value , record )
@@ -324,6 +315,7 @@ def type_name(plsql: Database, resolved: ResolvedName, plsql_type: Argument):
324315 WHERE object_id = :object_id
325316 AND position = :position
326317 AND subprogram_id = :subprogram_id
318+ AND data_level = 0
327319 """ ,
328320 object_id = resolved .object_id ,
329321 position = plsql_type .position ,
@@ -336,7 +328,7 @@ def type_name(plsql: Database, resolved: ResolvedName, plsql_type: Argument):
336328def python_type (
337329 plsql : Database , cursor : oracle .Cursor , resolved : ResolvedName , plsql_type : Argument
338330):
339- type_mapping = {
331+ plsql_types = {
340332 1 : oracle .STRING ,
341333 2 : oracle .NUMBER ,
342334 3 : oracle .NATIVE_INT ,
@@ -352,21 +344,53 @@ def python_type(
352344 }
353345
354346 try :
355- return cursor .var (type_mapping [plsql_type .datatype ])
347+ return cursor .var (plsql_types [plsql_type .datatype ])
356348 except KeyError :
357- converters = {
358- 122 : list_converter , # nested table
359- 123 : list_converter , # varray
360- 250 : record_converter , # plsql record
361- 251 : dict_converter , # plsql table
349+ out_converters = {
350+ 122 : list_out_converter , # nested table
351+ 123 : list_out_converter , # varray
352+ 250 : record_out_converter , # plsql record
353+ 251 : dict_out_coverter , # plsql table
362354 }
363355
364- converter = converters [plsql_type .datatype ]
356+ out_converter = out_converters [plsql_type .datatype ]
365357
366358 object_type = plsql ._connection .gettype (
367359 type_name (plsql = plsql , resolved = resolved , plsql_type = plsql_type )
368360 )
369- return cursor .var (object_type , outconverter = converter )
361+ return cursor .var (object_type , outconverter = out_converter )
362+
363+
364+ def find_matches (overloads , * positional , ** named ) -> Iterator [Overload ]:
365+ return (overload for overload in overloads if overload .match (* positional , ** named ))
366+
367+
368+ def filter_matches (filter_function , matches : Iterator [Overload ]) -> Overload :
369+ matches = list (filter (filter_function , matches ))
370+ if len (matches ) > 1 :
371+ raise ValueError ("Arguments matched with too many subprograms" )
372+ elif len (matches ) == 0 :
373+ raise ValueError ("Arguments do not match subprogram" )
374+ return matches [0 ]
375+
376+
377+ def translate_arguments (match_function ):
378+ def decorator (func ):
379+ @wraps (func )
380+ def wrapper (self : Subprogram , * positional , ** named ):
381+ match = filter_matches (
382+ match_function , find_matches (self .overloads , * positional , ** named )
383+ )
384+
385+ with self ._plsql ._connection .cursor () as cursor :
386+ result = func (self , match , cursor , positional , named )
387+
388+ if match .is_function :
389+ return result
390+
391+ return wrapper
392+
393+ return decorator
370394
371395
372396class Subprogram :
@@ -379,51 +403,36 @@ def __init__(
379403 group_by_overload (arguments = arguments ),
380404 )
381405
382- def _call_function (self , * args , ** kwargs ):
383- match = filter_match (self ._function_matches (* args , ** kwargs ))
384-
385- with self ._plsql ._connection .cursor () as cursor :
386- return cursor .callfunc (
387- self .resolved .name ,
388- python_type (
389- plsql = self ._plsql ,
390- cursor = cursor ,
391- resolved = self .resolved ,
392- plsql_type = match .return_type ,
393- ),
394- args ,
395- kwargs ,
396- )
397-
398- def _call_procedure (self , * args , ** kwargs ):
399- _ = filter_match (self ._procedure_matches (* args , ** kwargs ))
406+ @translate_arguments (match_function = lambda x : x .is_function )
407+ def _call_function (self , match : Overload , cursor , positional , named ):
408+ return cursor .callfunc (
409+ self .resolved .name ,
410+ python_type (
411+ plsql = self ._plsql ,
412+ cursor = cursor ,
413+ resolved = self .resolved ,
414+ plsql_type = match .return_type ,
415+ ),
416+ positional ,
417+ named ,
418+ )
400419
401- with self ._plsql ._connection .cursor () as cursor :
402- cursor .callproc (self .resolved .name , args , kwargs )
420+ @translate_arguments (match_function = lambda x : not x .is_function )
421+ def _call_procedure (self , match : Overload , cursor , positional , named ):
422+ _ = match
423+ cursor .callproc (self .resolved .name , positional , named )
403424
404425 def __call__ (self , * args , ** kwargs ):
405426 if self .overloaded and self .is_function and self .is_procedure :
406427 raise NotImplementedError (
407- "Subprogram is overloaded as a function and procedure, use _call_(procedure/function) method "
428+ "Subprogram is overloaded as a function and procedure, use _call_procedure or _call_function methods "
408429 )
409430
410431 if self .is_function :
411432 return self ._call_function (* args , ** kwargs )
412433 else :
413434 return self ._call_procedure (* args , ** kwargs )
414435
415- def _function_matches (self , * args , ** kwargs ) -> Iterator [Overload ]:
416- return filter (lambda x : x .is_function , self ._matches (* args , ** kwargs ))
417-
418- def _procedure_matches (self , * args , ** kwargs ) -> Iterator [Overload ]:
419- return filter (lambda x : not x .is_function , self ._matches (* args , ** kwargs ))
420-
421- def _matches (self , * args , ** kwargs ) -> Iterator [Overload ]:
422- """returns overloads that match with provided parameters"""
423- return (
424- overload for overload in self .overloads if overload .match (* args , ** kwargs )
425- )
426-
427436 @property
428437 def overloaded (self ) -> bool :
429438 """returns true if exists multiple definitions of the same subprogram in a package
@@ -496,7 +505,7 @@ def __getattr__(self, item) -> Union[Schema, Package, Subprogram]:
496505 except (oracle .DatabaseError , NotFound ):
497506 if self .is_schema (schema_name = item ):
498507 return Schema (plsql = self , name = item )
499- raise
508+ raise NotFound
500509 else :
501510 if found_object := search_object (plsql = self , name = name , item = item ):
502511 return found_object
0 commit comments