22
33from collections import namedtuple
44from enum import IntEnum
5- from typing import Tuple , Iterator
5+ from itertools import starmap
6+ from operator import itemgetter
7+ from typing import Iterator
8+ from typing import Tuple
69
710import cx_Oracle as oracle
811
@@ -144,9 +147,48 @@ def _exhaustive_name_resolution(
144147 raise NotFound (f"name { name } not found" )
145148
146149
150+ class Schema :
151+ def __init__ (self , plsql : Database , name : str ):
152+ self ._plsql , self ._name = plsql , name
153+
154+
147155class Function :
148- def __init__ (self , name : ResolvedName ):
149- self ._name = name
156+ def __init__ (self , plsql : Database , name : ResolvedName ):
157+ self ._plsql , self ._name = plsql , name
158+
159+
160+ class Query :
161+ def __init__ (
162+ self , connection : oracle .Connection , sql : str , * positional_binds , ** named_binds
163+ ):
164+ if all ([positional_binds , named_binds ]):
165+ raise ValueError ("Can not bind both by position and name" )
166+
167+ binds = positional_binds or named_binds
168+
169+ self ._connection , self .sql , self .binds = (connection , sql , binds )
170+
171+ def _execute (self ):
172+ with self ._connection .cursor () as cursor :
173+ cursor .execute (self .sql , self .binds )
174+
175+ if len (cursor .description ) > 1 :
176+ record_type = namedtuple (
177+ "Record" , (column [0 ].lower () for column in cursor .description )
178+ )
179+ records = starmap (record_type , cursor )
180+ else :
181+ records = map (itemgetter (0 ), cursor )
182+
183+ for record in records :
184+ yield record
185+
186+ @property
187+ def first (self ):
188+ return next (self ._execute ())
189+
190+ def __iter__ (self ):
191+ return self ._execute ()
150192
151193
152194class Database :
@@ -167,11 +209,17 @@ def __init__(
167209 def __getattr__ (self , item ):
168210 try :
169211 name = self ._name_resolve (item )
170- except oracle .DatabaseError :
171- raise AttributeError
212+ except (oracle .DatabaseError , NotFound ):
213+ if self .query (
214+ """SELECT COUNT(*) FROM all_users WHERE username = UPPER(:username)""" ,
215+ username = item ,
216+ ).first :
217+ return Schema (plsql = self , name = item )
172218
173- if name .object_type == ObjectTypes .function :
174- return Function (name )
219+ raise AttributeError
220+ else :
221+ if name .object_type == ObjectTypes .function :
222+ return Function (plsql = self , name = name )
175223
176224 raise AttributeError
177225
@@ -198,8 +246,8 @@ def _name_resolve(self, name: str) -> ResolvedName:
198246 object_number ,
199247 )
200248
201- def query (self , sql : str , * args , ** kwargs ) :
202- pass
249+ def query (self , sql : str , * positional_binds , ** named_binds ) -> Query :
250+ return Query ( self . _connection , sql , * positional_binds , ** named_binds )
203251
204252 def execute (self , statement : str , * args , ** kwargs ) -> None :
205253 with self ._connection .cursor () as cursor :
0 commit comments